如何将数据从Javascript传递到PHP,反之亦然?

如何通过Javascript脚本请求PHP页面并将数据传递给它?然后,如何让PHP脚本将数据传递回Java脚本?


client.js:


data = {tohex: 4919, sum: [1, 3, 5]};

// how would this script pass data to server.php and access the response?

server.php:


$tohex = ... ; // How would this be set to data.tohex?

$sum = ...; // How would this be set to data.sum?

// How would this be sent to client.js?

array(base_convert($tohex, 16), array_sum($sum))


胡子哥哥
浏览 558回答 3
3回答

至尊宝的传说

从PHP传递数据很容易,您可以使用它生成JavaScript。另一种方法则比较困难-您必须通过Javascript请求来调用PHP脚本。一个示例(为简单起见,使用传统的事件注册模型):<!-- headers etc. omitted --><script>function callPHP(params) {&nbsp; &nbsp; var httpc = new XMLHttpRequest(); // simplified for clarity&nbsp; &nbsp; var url = "get_data.php";&nbsp; &nbsp; httpc.open("POST", url, true); // sending as POST&nbsp; &nbsp; httpc.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");&nbsp; &nbsp; httpc.setRequestHeader("Content-Length", params.length); // POST request MUST have a Content-Length header (as per HTTP/1.1)&nbsp; &nbsp; httpc.onreadystatechange = function() { //Call a function when the state changes.&nbsp; &nbsp; &nbsp; &nbsp; if(httpc.readyState == 4 && httpc.status == 200) { // complete and no errors&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert(httpc.responseText); // some processing here, or whatever you want to do with the response&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; };&nbsp; &nbsp; httpc.send(params);}</script><a href="#" onclick="callPHP('lorem=ipsum&foo=bar')">call PHP script</a><!-- rest of document omitted -->不管get_data.php产生什么,它将出现在httpc.responseText中。错误处理,事件注册和跨浏览器XMLHttpRequest兼容性留给读者简单的练习;)

慕村225694

有几种方法,最主要的是获取表单数据或获取查询字符串。这是使用JavaScript的一种方法。当您单击链接时,它将调用_vals('mytarget','theval'),后者将提交表单数据。页面发回时,您可以检查是否已设置此表单数据,然后从表单值中检索它。<script language="javascript" type="text/javascript">&nbsp;function _vals(target, value){&nbsp; &nbsp;form1.all("target").value=target;&nbsp; &nbsp;form1.all("value").value=value;&nbsp; &nbsp;form1.submit();&nbsp;}</script>或者,您可以通过查询字符串获取它。PHP具有_GET和_SET全局函数来实现此目的,从而使其变得更加容易。我敢肯定,还有更多更好的方法,但是这些只是我脑海中浮现的一些方法。编辑:从其他人使用上述方法所说的内容出发,您将拥有一个锚标记,例如<a onclick="_vals('name', 'val')" href="#">My Link</a>然后在您的PHP中,您可以使用$val = $_POST['value'];因此,当您单击使用JavaScript的链接时,它将发布表单数据,并且页面从该单击发回时,您可以从PHP中检索它。
打开App,查看更多内容
随时随地看视频慕课网APP