繁体   English   中英

Javascript XMLHTTPREQUEST 在本地主机上发送 GET

[英]Javascript XMLHTTPREQUEST Post sending GET on localhost

我正在尝试使用纯 javascript XMLHTTPREQUEST 库发布表单数据。 My javascript function first gets all the html form data and cleans it as well as check that it is the right format before sticking it in an Object.
然后使用普通请求库发送带有正确标头的JSON.stringify(Object) 问题是我正在我的 Apache localhost 上对其进行测试,它不会将数据发送到指定的 php 文件。 它仅将数据连接到我的 Url header 作为 GET 请求。

        let reqObj = new XMLHttpRequest();
        var elem = document.getElementById(msgContan);
        //add event listener for request
        reqObj.addEventListener("progress", function(eve) {
            if (eve.lengthComputable) {
                //show progress on download using view
                jsView.elementShowMover(elem, strPos,endPos,moveMs);
                document.getElementById(msgElemnt).innerText = Math.round(eve.loaded/eve.total * 100) + "% Complete";
            }
        });
        reqObj.addEventListener("load", function(eve) {
            if (reqObj.status >= 200 && reqObj.status < 300) {
                //elem.style.display = "none";
                console.log('Completed');
            }
        });
        reqObj.addEventListener("error", function(eve) {
            document.getElementById(msgElemnt).innerText = "Failed to post data.";
        });
        reqObj.addEventListener("abort", function(eve) {
            document.getElementById(msgElemnt).innerText = "Data post was cancelled.";
        });
        //set timeout @ 30 seconds
        reqObj.timeout = 30000;
        //open network request
        reqObj.open('POST', 'localhost/myprojects/pages/app/web_app/getter.php');
        //set http-headers
        reqObj.setRequestHeader('Content-Type', 'application/json');
        //send the request
        reqObj.send(JSON.stringify(answ.jObj));

有人可以帮助我了解为什么会发生这种情况以及如何在本地主机上测试 POST 请求吗?

@epascarello 给出了正确的诊断来解决我的问题。 因此我发布它。
连接到我的 URL 的数据和不断发送的 GET 请求,即使请求了POST ,也是由于我

不取消表单提交。

取消表单提交取决于如何调用 XmlHttpRequest object。 在我的例子中,我调用了 function ,其中onclick事件绑定到 html <button>

该按钮没有设置类型属性,这意味着它默认提交。

我将按钮属性更改为type='button'取消了表单提交。

My second problem of not executing the php file or completing the request within the set javascript load event function was due to the XmlHttpRequest .send property's second parameter not set as a relative path. 因此,我的错误路径显示了

网络请求

404 Not Found with Request URL:http://localhost/myprojects/pages/localhost/myprojects/pages/app/web_app/getter.php
通过将我的绝对路径更改为相对路径, POST请求已完成。

暂无
暂无

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

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