Didn"t forge 2016-04-05 13:38 采纳率: 25%
浏览 23

检索POST JSON响应

I'm writing my first Ajax request, on a Groovy/Grails platform.

    var newDataB = $.ajax({
    method:'post',
    url: url,
    async: false,
    data: {source:"${source}"},
    success: function (response) { 
        jsonData = response;
        var res = JSON.parse(jsonData);
                alert(res);//
    }
});

Here is the response of my controller "url"

    def result = [ value: 'ok' ]
    render result as JSON

But it does not work and i get an error message in my browser

SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data 
var res = JSON.parse(jsonData);

I don't understand , the response seems to be a nice formatted JSON ?

EDIT i did a print as Paul suggests :

If i execute

    var newDataB = $.ajax({
    method:'post',
    url: url,
    async: false,
    dataType: 'json',
    data: {source:"${source}"},
    success: function (response) { 
        console.log(response)
        console.log(response.value)
        jsonData = response;
    }
});

The first print is :

Object { value="ok"}

The second print is

ok

If i want to get the result, how is the proper way ?

Do i have to assign the value inside the statement "success: function (response) { "

doing something like

var result

var newDataB = $.ajax({
    method:'post',
    url: url,
    async: false,
    dataType: 'json',
    data: {source:"${source}"},
    success: function (response) { 
    result = response.value
    }
});

console.log("result : "+result);

This code works for me !!

Or perhaps there is a way to get the result, doing something like

var newDataB = $.ajax({
    method:'post',
    url: url,
    async: false,
    dataType: 'json',
    data: {source:"${source}"},
    success: function (response) { 

    }
});

var result = newDataB.response.somethingblablabla

or

var result = OneFunction(newDataB.response)

??????

  • 写回答

2条回答 默认 最新

  • weixin_33686714 2016-04-05 13:45
    关注

    You shouldn't need to parse it, if your server is providing json.

    You can use dataType though to force jQuery to use a particular type:

    var newDataB = $.ajax({
        method:'post',
        url: url,
        async: false,
        dataType: 'json',
        data: {source:"${source}"},
        success: function (response) { 
            console.log(response);
    
        }
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度