我是php / javascript的初学者,我正在尝试使用php中准备好的语句访问Mysql数据库。一旦获得所需的行,我想将其发送到Javascript以进行处理(比较,增量...),我检查了类似的问题,但大多数问题都提出了与此类似的解决方案:
echo 'var result= ' . json_encode($exampleArray) . ';';
我不想打印数据结果,而是将其发送到javascript?我该怎么办?
请注意
echo 'var result= ' . json_encode($exampleArray) . ';';
与打印无关。在服务器端,这将创建要发送到客户端的页面的内容。客户端页面具有javascript变量结果供您处理(比较,递增...)。您应使用
JSON.parse()
可用于检索子集值并继续您的过程。
您应该考虑使用ajax来进行其他操作。您可以通过Javascript端向php脚本发送请求,该请求将计算所有内容并以字符串形式发送回所需数据。然后,您可以在Javascript中使用该字符串,而无需在前端打印该值。
在使用字符串之前首先发送一个ajax请求。
$.ajax('/ajax.php',
{
dataType: 'json', // type of response data
timeout: 500, // timeout milliseconds
success: function (data,status,xhr) { // success callback function
//Your string is inside data.responss
},
error: function (jqXhr, textStatus, errorMessage) { // error callback
$('p').append('Error: ' + errorMessage);
}
});
然后在您的ajax.php文件中以json格式回显var
<?php
// [...]
$data["responss"] = 2000;
echo json_encode($data);
?>