doumou8527 2015-01-08 04:46
浏览 393
已采纳

JSon解析我的代码返回错误

<script type="text/javascript">
$(document).ready(function(){
var obj = "";
var param = [{ "name": "id", value: 9}];   
$.ajax({
  type: 'POST',
  url: '2.php',
  data: param,
  success: function(dataFetch) {
var obj = JSON.parse(dataFetch);
alert(obj[0].name);
 },
  dataType: 'json',
  async:false
});
});
</script>

above is my code. The return result of 2.php is

{"name":"Halford Tee","type":"client","mobile":"1234567","location":"","description":""}

It give me an error

Uncaught SyntaxError: Unexpected end of input

When I remove this part

var obj = JSON.parse(dataFetch);
alert(obj[0].name);

The error is gone. Is there anything wrong with my code?


After looking at valuable guide from fellow programer

My 2.php returns

{"name":"David Tan","type":"leads","mobile":"91234567","location":"","description":""}

I tried the following

$(document).ready(function(){
var obj = "";
var param = [{ "name": "eventId", value: 9}];   
$.ajax({
  type: 'POST',
  url: '2.php',
  data: param,
  success: function(dataFetch) {
alert(dataFetch[0].name);
 },
  dataType: 'json',
  async:false
});
});

It give me an error

cannot read property 'name' of undefined.
  • 写回答

3条回答 默认 最新

  • douyimiao1993 2015-01-08 05:11
    关注

    when you use dataType: 'json' in your ajax then you don't need to use JSON.parse. your data will automatically be parsed in json format.so you can directly use it.

     use : `alert(dataFetch.name);`// you do not have any array so directly use it.your data is an object not array of object.
    

    note: i think you should use async:false only when your calling has to complete before the next statement in your function can be called.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思