gpt4 book ai didi

javascript - 如何使用POST方法来实现呢?

转载 作者:行者123 更新时间:2023-11-28 13:55:32 24 4
gpt4 key购买 nike

我在互联网上阅读了有关 GETPOST 的内容,对此我感到很困惑。我理解大部分内容,但是,我有一些困惑,比如我应该使用 GET 方法从操作页面获取(检索)数据吗?我们不能更改服务器数据(编辑、删除、更新),而 post 用于仅发布服务器上的数据,我们可以用它来做(编辑、删除、更新)。就像我有以下示例一样,我对如何使用 POST 方法使其感到困惑?而且我没有参数可以传入 url。我也看到,我无法使其异步。

 xmlhttp = new XMLHttpRequest();
var url = "/TinyEditor/XML/PreviewBody.xml"
xmlhttp.open("GET", url, false);
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send();
// alert(xmlhttp);
var xmlDoc;
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
xmlDoc = xmlhttp.responseXML;
// alert(xmlDoc);
}
}

当我对上述代码使用 POST 方法时,出现错误,

<title>The HTTP verb POST used to access path '/TinyEditor/XML/PreviewBody.xml' is not allowed

为什么会这样?

最佳答案

xmlhttp = new XMLHttpRequest();
var url = "/TinyEditor/XML/PreviewBody.xml"
xmlhttp.open("POST", url, false);
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(post_variable); //I have changed this
// alert(xmlhttp);
var xmlDoc;
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
xmlDoc = xmlhttp.responseXML;
// alert(xmlDoc);
}
}

然后像这样制作post_variable

post_variable=field_name=value&field_name2=value2

记住使用encodeURIComponent(value)对值进行编码

例如你的字符串看起来像这样

post_variable = "name=" + encodeURIComponent("this is my name") + "&last_name=" + encodeURIComponent("this is my last name");

希望这有帮助

我建议您开始使用jQuery它是轻量级的,并且比您定制的脚本更容易使用。所以基本上如果你使用 jQuery 你可以这样做

$.ajax({ 
url: '/TinyEditor/XML/PreviewBody.xml', //read xml
type: 'post', //method type
dataType: 'xml', //can be json, html, xml etc
data: $('#form_id').serialize(), //this will collect form values
success: function(d) { alert(d); } //this method will be executed once done
});

仅此而已,您不必担心任何事情,例如浏览器版本、浏览器类型或类似的事情。

关于javascript - 如何使用POST方法来实现呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8135287/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com