1.

客户端代码:

$.ajax({
    data: {
        name: 'zhangsan'
    },
    url: apiUrl.getTwo('TestFourth'),
    dataType: 'jsonp',
    success: function (data) {
        alert(data);
    },
    error: function (XMLRequest, textStatus) {
        console.info(XMLRequest);
        console.info(textStatus);
        alert('失败');
    }
});

2.使用Controller的Action返回字符串类型,从从服务端返回的总是字符串,给字符串添加了双引号,所以在Jquery的jsonp返回函数中解析失败

[HttpGet]
public string TestTwo(string callback)
{
    string json = "{'name':'张三','age':'20'}";
    string result = string.Format("{0}({1})", callback, json);
    return result;
}

返回结果:

Jquery JSOPN在WebApi中的问题

3.手动输出结果,不待双引号解析成功

[HttpGet]
public void TestThree(string callback)
{
    string json = "{'name':'张三','age':'20'}";
    string result = string.Format("{0}({1})", callback, json);
    //使用当前HttpResponseBase输入结果
    ReqHelper.resp.Write(result);
    //在WebApi中需要手动输出缓存内容
    ReqHelper.resp.End();
}

[HttpGet]
public void TestFourth(string callback)
{
    object obj = new { name = "李四", age = 25 };
    string json = obj.ToJsonString();
    string result = string.Format("{0}({1})", callback, json);
    ReqHelper.resp.Write(result);
    ReqHelper.resp.End();
}

返回结果如:

Jquery JSOPN在WebApi中的问题

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-01-08
  • 2022-12-23
  • 2022-01-19
  • 2022-12-23
  • 2021-08-20
  • 2021-06-03
猜你喜欢
  • 2021-07-15
  • 2022-12-23
  • 2022-02-20
  • 2022-01-31
  • 2022-12-23
  • 2022-12-23
  • 2021-09-08
相关资源
相似解决方案