如何从 javascript 发布请求中获得响应
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14858130/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get a response from a javascript post request
提问by Ostap Hnatyuk
So I'm using this post request I found on here, but I'm wondering how I receive a response using this...
所以我正在使用我在这里找到的这个帖子请求,但我想知道我如何使用这个收到回复......
function post_to_url(path, params, method) {
method = method || "post";
var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", path);
for(var key in params) {
if(params.hasOwnProperty(key)) {
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", params[key]);
form.appendChild(hiddenField);
}
}ody.appendChild(form);
form.submit();
}
Thanks in advance.
提前致谢。
回答by naugtur
This code configures a form and submits it. You don't get any response to javascript, because the page reloads.
此代码配置一个表单并提交它。您没有收到任何对 javascript 的响应,因为页面会重新加载。
Try using jQuery: http://api.jquery.com/jQuery.post/
尝试使用 jQuery:http: //api.jquery.com/jQuery.post/
Or plain javascript AJAX: https://developer.mozilla.org/en/docs/AJAXif you want to write the whole thing yourself
或者普通的 javascript AJAX:https: //developer.mozilla.org/en/docs/AJAX如果你想自己写整件事