gpt4 book ai didi

javascript - 如何在 JavaScript 中获取 HTTP 回复?

转载 作者:行者123 更新时间:2023-12-03 11:02:46 25 4
gpt4 key购买 nike

在开始之前,请允许我解释一下情况。

  1. 我有一个 html(例如 A.html)页面,我可以在其中从表单获取信息。我将数据发送到 php 页面(例如 B.php)。

  2. B.php 处理表单并在屏幕上回显字符串。

  3. JavaScript 页面(例如 C.js)需要向 B.php 发送 HTTP 请求并读取回显的内容。

这样的事情可能吗?查了很多资料都没有解释。

最佳答案

您应该使用 AJAX。

它包含 3 个步骤:

  1. 创建 XMLHttpRequest 对象
  2. 设置onreadystatechange函数
  3. 通过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);

关于javascript - 如何在 JavaScript 中获取 HTTP 回复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28007799/

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