提交FORM数据然后返回响应

时间:2018-01-20 12:28:07

标签: javascript

我有以下代码将发布数据发送到我的表单并提醒预期结果,但是我发现很难将其保存为我可以在函数外部使用的变量,任何人都可以提供任何帮助吗?

<script>
var http = new XMLHttpRequest();
var url = "form.php";
var params = "name=test";
http.open("POST", url, 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) {
        alert(http.responseText);
    }
}
http.(params);
</script>

1 个答案:

答案 0 :(得分:0)

只需声明一个变量并在服务器响应请求时设置它;

var http = new XMLHttpRequest();
var url = "form.php";
var params = "name=test";
var response;
http.open("POST", url, 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) {
        alert(http.responseText);
        response = http.responseText;
    }
}
http.(params);