在AJAX到PHP请求之后,是否可以将变量从PHP发送回AJAX? [英] Is it possible to send variables back from PHP to AJAX after AJAX to PHP request?
问题描述
我有一个AJAX请求,该请求从PHP的SQL数据库中获取一些信息.
I have an AJAX request that fetches some info from a SQL database in PHP.
问题是,我需要使用变量将其发送回AJAX.不只是在屏幕上回显所有内容.
The problem is, I need to send it back to AJAX in variables. Not to just echo it all out on screen.
这可能吗?如果是这样,我将如何做这样的事情?
Is this possible? If so, how would I go about doing something like this?
谢谢.
推荐答案
Yes, you could json_encode the variable you want to send back to client.
echo json_encode( array('variable' => 'your value' ) );
请求完成后,客户端将通过回调接收数据.在没有更多细节说明的情况下,我可以提供更多细节,但我可以提供代码示例,具体取决于您使用的是JavaScript库(例如jQuery)还是原始XHR请求.
The client will receive the data through a callback when the request is completed. Without more clarification on specifics that's all i can offer, with some more details i can provide code samples depending on whether you're using a JavaScript library such as jQuery or doing a raw XHR request.
因此在jquery中检索上面的变量,您将执行以下操作.
so in jquery to retrieve the variable above you would do the following.
$.getJSON('yourfile.php', function(data){
console.log( data.variable );
});
这篇关于在AJAX到PHP请求之后,是否可以将变量从PHP发送回AJAX?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!