使用ajax

时间:2016-09-04 23:07:23

标签: php jquery ajax

我正在尝试学习Ajax和Json,所以我可以在它上面构建它以将PHP数据传递到我的网页而不需要刷新。 我使用以下示例,但结果html页面没有显示任何内容。有人可以让我知道我做错了什么。

Html代码

<html>
<body>

<script src="jquery.js"></script>
<script>
    $.ajax({
      url: "test.php",
      dataType: "json", //the return type data is jsonn
      success: function(data){ // <--- (data) is in json format
        alert(data.test1);
        //parse the json data
      }
    });
</script>
<div id = "data"></div>
</body>
</html>

PHP代码名为test.php

<?php

$test = array();
$test['test1'] = '1';
$test['test2'] = '2';
$test['test3'] = '3';

echo json_encode($test);
//echo nothing after this //not even html
?>

2 个答案:

答案 0 :(得分:2)

您需要在php中设置响应内容类型。

我认为jQuery会检查响应类型。

header("Content-Type: application/json");

还为错误添加绑定。

$.ajax({
  url: "test.php",
  dataType: "json", //the return type data is jsonn
  success: function(data){ // <--- (data) is in json format
    alert(data.test1);
    //parse the json data
  },
  error: function(jqXHR, textStatus, errorThrown) {
    alert("Error: " + textStatus);
  }
});

答案 1 :(得分:-1)

  1. 检查同一目录中的Jquery代码文件是否有效。
  2. 您的php文件也位于同一目录中。
  3. 您必须使用localhost运行您的html文件。