简体   繁体   English

发送ajax请求

[英]Send ajax request

Hello i have such code 您好我有这样的代码

<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();
}

I want to send this request async, but when i use xmlhttp.open(...,...,true) this request doens't even go to server, i watch it in google chrome console, but if i run sbt() function from console request goes ok, and if i use xmlhttp.open(...,...,false) it works fine, can someone help me? 我想发送此请求异步,但当我使用xmlhttp.open(...,...,true)这个请求甚至没有去服务器,我在谷歌Chrome控制台看,但如果我运行sbt()来自控制台请求的功能正常,如果我使用xmlhttp.open(...,...,false)它工作正常,有人可以帮助我吗? Thank you. 谢谢。

The submit button will immediately submit the form it is in, and the browser will leave the page (and the JavaScript execution environment from which the Ajax request is being made). 提交按钮将立即提交它所在的表单,浏览器将离开页面(以及从中发出Ajax请求的JavaScript执行环境)。

Cancel the default behaviour of the form submission when you want to use JavaScript instead. 当您想要使用JavaScript时,取消表单提交的默认行为。

onclick="sbt(); return false;"

(I'd look at using a modern approach to event binding instead of onclick attributes though). (我会考虑使用现代方法来进行事件绑定,而不是使用onclick属性)。

is this your entire page code? 这是您的整个页面代码吗?

Have you checked the jscript load order ? 你检查了jscript加载顺序吗?

please take a look at this---> fiddle (this has a 3 sec response delay ) 请看看这个---> 小提琴 (这有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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM