zoukankan      html  css  js  c++  java
  • Jquery JSOPN在WebApi中的问题

    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;
    }

    返回结果:

    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();
    }

    返回结果如:

  • 相关阅读:
    数组splice用法
    opacity 适配Ie
    直接贴页面,页面衔接处总会有一像素的间隔
    <script src='url'</script>显示问题
    弹出层
    CF789A. Anastasia and pebbles
    CF789C. Functions again
    HDU2161 Primes
    UVA11752 The Super Powers
    UVA11827 Maximum GCD
  • 原文地址:https://www.cnblogs.com/tianma3798/p/5092159.html
Copyright © 2011-2022 走看看