gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 21:30:50 26 4
gpt4 key购买 nike

如何通过 Javascript 脚本请求 PHP 页面并向其传递数据?那么我如何让 PHP 脚本将数据传递回 Javascript 脚本?

客户端.js:

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

服务器.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))

最佳答案

从 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.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 -->

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

另请参阅Mozilla's documentation更多示例

关于php - 如何将数据从 Javascript 传递到 PHP,反之亦然?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35281470/

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