繁体   English   中英

使用javascript ajax json检索php数组时出错

[英]got error when using javascript ajax json to retrieve php array

我的html页面是假设要从php页面检索数组,并警告数组中的第一个元素。 但是,当我运行html时,出现以下错误,“未捕获的TypeError:对象函数(E,F){返回新的o.fn.init(E,F)}”在控制台窗口中没有方法'parseJSON'“。 我尝试使用jQuery.parseJSON(json_data)代替$ .parseJSON(json_data),但仍然遇到相同的错误。 我怎样才能解决这个问题?

script.js:

function getArr(){                      
alert('return sent');           
$.ajax({              
url: "n1.php",             
 type: "GET",             
 success: function(json_data){                  
 var data_array =jQuery.parseJSON(json_data);                 
 var rec = data_array[0];                   
 alert(rec);                    
 alert("GOOD");              
 },               
 error: function() {                  
 alert("BAD");               
  }          });                     
 }

newcal.html:

<!DOCTYPE html>
<html >
<head>
<meta charset="utf-8">

<link rel="stylesheet" media="screen" href="demo.css">


<body onload="getArr();">
<div id="rounded"><div id="main" class="container">
<div id="pageContent"> 
Hello, this is the default content
</div>
</div>

</div>
</body>
<script type="text/javascript"          src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script     type="text/javascript" src="script.js"></script>
</head>
</html>

n1.php:

<?php

$output = array("cat","dog");
echo json_encode($output);
?>

parseJSON已在jQuery 1.4.1中添加(在2010年)

您正在使用的jQuery 1.3.2(2009年起)过旧。

jQuery 1.x的当前版本是1.11(今年发布)。

使用最新版本的jQuery。


您还应该告诉浏览器您正在向其发送JSON,而不是声称您的JSON是HTML。 (PHP默认声称通过Web服务器输出的任何内容都是HTML)

<?php
header("Content-type: application/json");
$output = array("cat","dog");
echo json_encode($output);
?>

然后让jQuery自动解析它:

success: function(data_array){                  
    // Remove the following line. It will be parsed automatically.
    // var data_array =jQuery.parseJSON(json_data);                 
    var rec = data_array[0];                   

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM