[英]Passing a PHP variable to JavaScript For AJAX Request
So my workflow is that onClick of an list element, my JS initiates a PHP AJAX request to build a card object. 因此,我的工作流程是列表元素的onClick,我的JS发起了一个PHP AJAX请求来构建卡片对象。 The $content is a card (similar to KickStarter) of topic data.
$ content是一张主题数据卡(类似于KickStarter)。 What I'm trying to do is a pass the 'topic_id' of each topic-instance so that I can then use it in the success function, to then initiate ANOTHER AJAX request (but to Discourse).
我想做的是传递每个主题实例的“ topic_id”,以便随后可以在成功函数中使用它,然后发起另一个AJAX请求(但发送给Discourse)。
With attempt 2), I get a null when viewing its value in the web inspector. 尝试2)时,在Web检查器中查看其值时得到一个null。
The AJAX requests (the console.log() of the variable I want to get returns a blank line in the web console): AJAX请求(我要获取的变量的console.log()在Web控制台中返回空行):
$.post( "/wp-content/mu-plugins/topic-search.php", { topicID: $topicFilter, filterBy: $sortByFilter },
function( data ) {
console.log(topic_id);
data = data.trim();
if ( data !== "" ) {
//get the participants data for avatars
$.getJSON('http://ask.example.com/t/' + topic_id + '.json', function() {
The end of topic-search.php, which echoes out the built up card. topic-search.php的末尾,它回显了已建立的卡。 Script is supposed to return the topic_id variable for use in the success function.
脚本应该返回在成功函数中使用的topic_id变量。
}
//One attempt: echo $content; //
//Another attempt: echo json_encode(array('data' => $content, 'topic_id' => $row['topicid']));//
}
?>
<script>
var topic_id = "<?php echo $row['topicid'] ?>";
</script>
Try this: 尝试这个:
In php 在PHP中
$inputJson = file_get_contents('php://input');
$input = json_decode($inputJson, true); //Convert JSON into array
In javascript 在JavaScript中
var $url = '/wp-content/mu-plugins/topic-search.php';
var $json = JSON.stringify({topicID: $topicFilter, filterBy: $sortByFilter});
$.ajax({
url: $url,
type: "POST",
data: $json,
dataType: "json",
success: function(data){//you will have the body of the response in data
//do something
},
error: function(data){
//do something else
}
});
EDIT: 编辑:
This will request $url
with the $json
data. 这将请求
$url
和$json
数据。 You will have it available on $input
on the server side as an array. 您可以将其作为数组在服务器端的
$input
上使用。 You can then on the server prepare a response with a json body that you will have available on the success function as the data
variable. 然后,您可以在服务器上准备一个带有json正文的响应,您可以在成功函数上将其用作
data
变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.