简体   繁体   English

如何在JavaScript中获得HTTP回复?

[英]How to get HTTP reply in javascript?

Before I satart, allow me to explain a situation. 在我坐下之前,请允许我解释一下情况。

  1. I have an html(say A.html) page where I get information from a form. 我有一个html(例如A.html)页面,可从表单中获取信息。 I send the data to a php page (say B.php). 我将数据发送到php页面(例如B.php)。

  2. B.php processes the form and echo a string on screen. B.php处理表单并在屏幕上回显字符串。

  3. A javascript page (Say C.js) needs to send an HTTP request to B.php and read what has been echoed. 一个javascript页面(说C.js)需要向B.php发送HTTP请求并读取已回显的内容。

Is such a thing even possible? 这样的事情有可能吗? I searched a lot and no explanation. 我搜索了很多,没有任何解释。

You should use AJAX. 您应该使用AJAX。

It concludes 3 steps : 它总结了3个步骤:

  1. Create XMLHttpRequest Object 创建XMLHttpRequest对象
  2. Set onreadystatechange function 设置onreadystatechange功能
  3. Post data via JS 通过JS发布数据

File A.html: 文件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> 

And the file b.php: 和文件b.php:

<?php 
$text = $_POST['text'];
echo "The length of your text $text is ".strlen($text);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM