如何测试我的XMLHttpRequest是否有效?

时间:2017-07-20 08:05:34

标签: javascript php post request

(抱歉英语不好)

我是js和php的初学者我想知道如何测试我的POST请求是否有效,

发送请求的代码:

var nom2 = document.getElementById('nom2').value;
var data2 = document.getElementById('image_upload').value;
returnValue = "nom2="+nom2+"&data2="+data2;
var requete = createXmlHttpRequestObject();
requete.open('POST', "photo2.php", true);
requete.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
requete.send(returnValue);

用于测试我的请求是否有效的代码

if (isset($_POST['nom2']) && isset($_POST['data2']))
{
    echo"<script  type='text/javascript'>   message(); </script>";
}

问题是没有任何内容写入控制台日志,当我尝试回复时,没有任何内容也被写入。需要一些帮助!

谢谢!

1 个答案:

答案 0 :(得分:0)

您必须创建一个回调。这是一个在浏览器完成请求时调用的函数。

var nom2 = document.getElementById('nom2').value;
var data2 = document.getElementById('image_upload').value;
var parameters = "nom2="+nom2+"&data2="+data2;

var http = new XMLHttpRequest();
http.open("POST", "photo2.php", true);

//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

http.onreadystatechange = function() {//Call a function when the state changes.
    if(http.readyState == 4 && http.status == 200) {
        console.log(http.responseText); // <= Here your browser prints the response that came from the php echo to the browser console
    }
}
http.send(parameters);