如何在 javascript 中获得 HTTP 回复?
How to get HTTP reply in javascript?
开始之前,请允许我解释一个情况。
我有一个 html(比如 A.html)页面,我可以在其中从表单获取信息。我将数据发送到 php 页面(比如 B.php)。
B.php 处理表单并在屏幕上回显字符串。
一个 javascript 页面(比如 C.js)需要向 B.php 发送 HTTP 请求并读取回显的内容。
这种事情有可能吗?我搜索了很多,没有解释。
你应该使用 AJAX.
它总结了 3 个步骤:
- 创建 XMLHttpRequest 对象
- 设置onreadystatechange函数
- Post 数据通过 JS
文件A.html:
<html>
<input id="text" type="text" value="Hello"/>
<input type="button" value="getResponse" onclick="getResponse();"/>
<script>
var xmlhttp;
//Create XMLHttpRequest Object
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
//this function will be triggered after "xmlhttp.send" finished
xmlhttp.onreadystatechange=function()
{
//readyState==4 means success, and status==200 means 'OK'
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert(xmlhttp.responseText);
}
}
// send post data via your web element
function getResponse(){
var text = document.getElementById("text").value;
//send data and get response
xmlhttp.open("POST","b.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("text="+text);
}
</script>
</html>
和文件 b.php:
<?php
$text = $_POST['text'];
echo "The length of your text $text is ".strlen($text);
开始之前,请允许我解释一个情况。
我有一个 html(比如 A.html)页面,我可以在其中从表单获取信息。我将数据发送到 php 页面(比如 B.php)。
B.php 处理表单并在屏幕上回显字符串。
一个 javascript 页面(比如 C.js)需要向 B.php 发送 HTTP 请求并读取回显的内容。
这种事情有可能吗?我搜索了很多,没有解释。
你应该使用 AJAX.
它总结了 3 个步骤:
- 创建 XMLHttpRequest 对象
- 设置onreadystatechange函数
- Post 数据通过 JS
文件A.html:
<html>
<input id="text" type="text" value="Hello"/>
<input type="button" value="getResponse" onclick="getResponse();"/>
<script>
var xmlhttp;
//Create XMLHttpRequest Object
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
//this function will be triggered after "xmlhttp.send" finished
xmlhttp.onreadystatechange=function()
{
//readyState==4 means success, and status==200 means 'OK'
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert(xmlhttp.responseText);
}
}
// send post data via your web element
function getResponse(){
var text = document.getElementById("text").value;
//send data and get response
xmlhttp.open("POST","b.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("text="+text);
}
</script>
</html>
和文件 b.php:
<?php
$text = $_POST['text'];
echo "The length of your text $text is ".strlen($text);