PHP没有将数据值返回给jquery.ajax()

时间:2014-05-14 00:15:50

标签: php jquery ajax

我使用以下一组测试文件发送,并在JS和PHP之间获取Ajax请求/响应。以下是文件:

HTML:

<form id="foo">
    <label for="bar">A bar</label>
    <input id="bar" name="bar" type="text" value="" />
    <input type="submit" value="Send" />
</form>

<!-- The result of the search will be rendered inside this div -->
<div id="result"></div>

JavaScript的:

$(document).ready(function() {
/* Attach a submit handler to the form */
$("#foo").submit(function(event) {

    /* Stop form from submitting normally */
    event.preventDefault();

    /* Clear result div*/
    $("#result").html('');

    /* Get some values from elements on the page: */
    var values = $(this).serialize();

    /* Send the data using post and put the results in a div */
    $.ajax({
        url: "test.php",
        type: "post",
        data: values,
        success: function(data){
                alert(data.returned_val);
        },
        error:function(){
            alert("failure");
            $("#result").html('There is error while submit');
        }
    });
});
});

PHP:

<?php
  $id = $_POST['bar'];
  echo json_encode(array('returned_val' => 'yoho'));
?>

测试步骤:

  1. 在浏览器中打开html
  2. 在文本字段中输入&#34;测试&#34;
  3. 点击提交按钮
  4. 结果:警告框说:&#34; undefined&#34;。

    我错过了什么?

0 个答案:

没有答案