发送ajax请求

时间:2014-07-22 14:20:01

标签: javascript ajax

您好我有这样的代码

<button onclick="sbt()" name="step1[save]" type="submit" class="btn-type5 next-btn-form pie" value="Далее">Send</button>
function sbt(){
var phone = document.getElementById('fld1').value;
        var xmlhttp;
        if (window.XMLHttpRequest)
        {
                xmlhttp=new XMLHttpRequest();
        }
        else
        {
                xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }}
        xmlhttp.open("GET","host.com/send.php?phone="+phone+"&t="+Date.now(),true);
        xmlhttp.send();
}

我想发送此请求异步,但是当我使用xmlhttp.open(...,...,true)这个请求甚至没有去服务器,我在谷歌Chrome控制台中观看,但是如果我从控制台运行sbt()功能请求没问题,如果我使用xmlhttp.open(...,...,false)它工作正常,有人可以帮助我吗?谢谢。

2 个答案:

答案 0 :(得分:2)

提交按钮将立即提交其所在的表单,浏览器将离开页面(以及从中发出Ajax请求的JavaScript执行环境)。

当您想要使用JavaScript时,取消表单提交的默认行为。

onclick="sbt(); return false;"

(我会考虑使用modern approach to event binding代替onclick属性。)

答案 1 :(得分:1)

这是您的整个页面代码吗?

你检查过jscript加载顺序吗?

请看一下这个---&gt; fiddle(这有3秒的响应延迟)

<h2>AJAX async demo</h2>

<button type="button" onclick="callAjax()">Request data</button>
<div id="testDiv"></div>

<script>
function callAjax() {

    var xmlhttp;
    if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    } else { // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function () {

        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.getElementById("testDiv").innerHTML = xmlhttp.responseText;
        }
    };

    xmlhttp.open("POST", "/echo/html/", true);
    var params = "html=test&delay=3"
    xmlhttp.send(params);
}
</script>