gpt4 book ai didi

javascript - 通过http请求发送字符串

转载 作者:行者123 更新时间:2023-12-03 11:16:22 24 4
gpt4 key购买 nike

我刚刚开始学习如何使用 XMLHttpRequest,我从 this 开始来自 w3schools 的示例,我想修改它以发送字符串。这是新代码:

<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc() {
var xmlhttp;
var str="sent string";
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send(str);
alert(xmlhttp.responseText);
}
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>

我想输出响应并查看字符串是否已发送但警报不返回任何内容。只是一个空窗子。我做错了什么?

另外,我在这个 question 中找到了一个例子它还添加了这些代码行:

http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");

它们总是必要的吗?如果是,为什么?该页面的代码也发送一个字符串,但该代码对我也不起作用。

编辑:这是我更新后的代码,仍然不起作用。我什至在不发送字符串的情况下尝试过,但仍然没有任何反应。我不再在 w3wschools 中尝试它,而是在正确的位置,我不再将代码放在函数中,并进行了 @Quentin 告诉我的更改:

<script>
var xmlhttp=null;
var str="sent_string";
xmlhttp=new XMLHttpRequest();
xmlhttp.open("POST","http://192.168.1.3:80",true);
xmlhttp.setRequestHeader("Content-type", "text/plain");
xmlhttp.setRequestHeader("Content-length", str.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(str);
xmlhttp.addEventListener('load', function () {
alert(this.responseText);
alert(xmlhttp.readyState);}
);
</script>

最佳答案

首先,在尝试警告该值之前,您不会等待 HTTP 响应。

alert(xmlhttp.responseText);

应该是:

xmlhttp.addEventListener('load', function () {
alert(this.responseText);
});

第二,您正在发出带有消息正文的 GET 请求。如果您想发送请求正文,则需要 POST(或 PUT)请求:

xmlhttp.open("POST","ajax_info.txt",true);

第三,您发送纯文本请求,但告诉服务器它是表单编码的。

http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

应该是

xmlhttp.setRequestHeader("Content-type", "text/plain");

关于javascript - 通过http请求发送字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27324345/

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