将jquery值传递给php变量

时间:2012-02-02 16:54:11

标签: php jquery variables assign

我是一个菜鸟,所以希望你能帮忙!

我有以下jquery代码:

$("#single-home-container").html(post_id);

然后它会在页面上的HTML中显示我想要的值:

<div id="single-home-container"></div>

我想要的是将值传递给PHP变量,我可以使用MySQL查询中的信息。 我该怎么办?它在WordPress中,所以没有单独的文件

由于

2 个答案:

答案 0 :(得分:1)

你需要使用ajax。像这样:

JQuery的:

$('.locationID').click(function(){ 
    var post_id = $(this).attr('rel'),
        $container = $("#single-home-container");
        old_html = $container.html();

    $container.html('loading...');
    $.ajax({
        url : '/path/to/php/file.php',
        data:{"post_id":post_id},
        type: 'post',
        dataType: 'json',
        success: function(data){
            $container.html(data.postBody);
        },
        error: function(data){
            // possibly notify the user of the error
            $container.html(old_html);
        }
    });
});

假设您的帖子表中有一个名为postBody的字段

PHP

<?php
    header('Content-type: application/json');
    // $query_result = do mysql query with $_POST['post_id']
    echo json_encode($query_result);
    exit();
?>

假设您想要所有字段并且您要返回所有字段,包括postBody - 当然您还有PHP 5.2.6+或他们添加的任何版本json_encode()

答案 1 :(得分:0)

您可以使用 jQuery.post() jQuery.ajax()

这里有一些例子:

<script>
    $.post("test.php", { "func": "getNameAndTime" },
     function(data){
       console.log(data.name); // John
       console.log(data.time); //  2pm
     }, "json");
</script>

<script>
$.ajax({
  url: "test.html",
  context: document.body,
  success: function(){
    $(this).addClass("done");
  }
});
</script>
相关问题