doushi3189 2016-02-29 23:27
浏览 52

将PHP变量传递给JavaScript以获取AJAX请求

So my workflow is that onClick of an list element, my JS initiates a PHP AJAX request to build a card object. The $content is a card (similar to KickStarter) of topic data. 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).

With attempt 2), I get a null when viewing its value in the web inspector.

The AJAX requests (the console.log() of the variable I want to get returns a blank line in the web console):

$.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. Script is supposed to return the topic_id variable for use in the success function.

    }


    //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>

  • 写回答

1条回答 默认 最新

  • dongxie7683 2016-02-29 23:55
    关注

    Try this:

    In php

    $inputJson = file_get_contents('php://input');
    $input = json_decode($inputJson, true); //Convert JSON into array
    

    In 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. You will have it available on $input on the server side as an array. 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.

    评论

报告相同问题?

悬赏问题

  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?