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

dat*_*.io 11 javascript php

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

client.js:

data = {tohex: 4919, sum: [1, 3, 5]};
// how would this script pass data to server.php and access the response?
Run Code Online (Sandbox Code Playgroud)

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))
Run Code Online (Sandbox Code Playgroud)

Pis*_*3.0 19

从PHP传递数据很简单,您可以使用它生成JavaScript.另一种方式有点难 - 你必须通过Javascript请求调用PHP脚本.

一个例子(为简单起见,使用传统的事件注册模型):

<!-- headers etc. omitted -->
<script>
function callPHP(params) {
    var httpc = new XMLHttpRequest(); // simplified for clarity
    var url = "get_data.php";
    httpc.open("POST", url, true); // sending as POST

    httpc.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    httpc.setRequestHeader("Content-Length", params.length); // POST request MUST have a Content-Length header (as per HTTP/1.1)

    httpc.onreadystatechange = function() { //Call a function when the state changes.
        if(httpc.readyState == 4 && httpc.status == 200) { // complete and no errors
            alert(httpc.responseText); // some processing here, or whatever you want to do with the response
        }
    };
    httpc.send(params);
}
</script>
<a href="#" onclick="callPHP('lorem=ipsum&foo=bar')">call PHP script</a>
<!-- rest of document omitted -->
Run Code Online (Sandbox Code Playgroud)

无论get_data.php产生什么,都会出现在httpc.responseText中.错误处理,事件注册和跨浏览器XMLHttpRequest兼容性留给读者简单的练习;)

  • 值得注意的是,由于Same-origin-policy,它仅适用于相对URL:http://en.wikipedia.org/wiki/Same-origin_policy (2认同)

Ter*_*ang 9

前几天我遇到了类似的问题.说,我想将数据从客户端传递到服务器并将数据写入日志文件.这是我的解决方案:

我简单的客户端代码:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"   "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
   <title>Test Page</title>
   <script>
    function passVal(){
        var data = {
            fn: "filename",
            str: "this_is_a_dummy_test_string"
        };

        $.post("test.php", data);
    }
    passVal();
   </script>

</head>
<body>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

和服务器端的PHP代码:

<?php 
   $fn  = $_POST['fn'];
   $str = $_POST['str'];
   $file = fopen("/opt/lampp/htdocs/passVal/".$fn.".record","w");
   echo fwrite($file,$str);
   fclose($file);
?>
Run Code Online (Sandbox Code Playgroud)

希望这适合您和未来的读者!


Jas*_*n S 7

我使用JSON作为格式,使用Ajax(实际上是XMLHttpRequest)作为客户端 - >服务器机制.