如何ajax POST到php页面并返回PHP页面的输出?

时间:2014-05-23 17:55:56

标签: php jquery ajax

我有以下代码来向我的test.php文件ajax POST请求。然后,我想将test.php的输出加载到<div id="here"></div>

我的test.php文件包含以下内容:

var_dump($_POST);
die();

这是jQuery:

<script type="text/javascript">
$(document).ready(function(e)
{
    $('#here').find('a').on('click', function(e) // listens for <a href> click
    {
        e.preventDefault();
        $.ajax({
              type: "POST",
              url: "test.php",
              data: { foo: "bar", working: "yes" }
            })
        $('#here').load('test.php');    // get the output of test.php
    });
});
</script>

我从test.php页面返回一个空的$ _POST数组。我做错了什么?

2 个答案:

答案 0 :(得分:1)

你应该这样写:

    $.ajax({
          type: "POST",
          url: "test.php",
          data: { foo: "bar", working: "yes" },
          success : function(response) {
               $('#here').html(response);
          }
        });

因为$.load()方法默认调用GET查询。并且没有必要两次调用ajax。

答案 1 :(得分:0)

$('#here').find('a').on('click', function(e) // listens for <a href> click
{
    e.preventDefault();
    $.ajax({
          type: "POST",
          url: "test.php",
          data: { foo: "bar", working: "yes" },
          success: function(result){
                    $('#here').html(result);
             }
        })  
});

您需要在ajax中添加成功函数才能获得结果