通过http请求发送字符串

时间:2014-12-05 20:41:43

标签: javascript string xmlhttprequest

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

<!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>

2 个答案:

答案 0 :(得分:1)

首先,在尝试提醒值之前,您不是在等待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");

答案 1 :(得分:0)

如果你想发送带有ajax请求的东西,有两种方法,POST和GET。

在发送任何内容之前,您必须阅读相关内容。只是Google for REST或HTTP POST。你会发现一切。

我建议您使用AngularJS或jQuery,而不是原始的ajax调用。

例如在AngularJS中,您所要做的就是:

$http.get('mypage.php?name=john').success(function (data) {

//work with the answer in data

});