zoukankan      html  css  js  c++  java
  • jsonp的使用记录

    最近前端的同事说要写一个手机查看的html5页面,需要我提供数据。

    这个很ok啊,立马写了个服务返回数据。但是对方调用不了,因为跨域了。

    返回错误如下:

     Failed to load xxxxxx: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:100' is therefore not allowed access.
     
    解决方案
    使用jsonp。
    关于这个,我查看了这篇文章,讲的非常清楚了。点击这里查看
     
    后台返回格式
     
    一开始返回使用的是string类型,但这个不起作用,字符串不会识别为可执行的js代码。
     
     HttpContext.Current.Response.Write(callback + "(" + JsonConvert.SerializeObject(r) + ")");
                    HttpContext.Current.Response.End();

    前台调用

     1     jQuery(document).ready(function () {
     2         $.ajax({
     3             type: "get",
     4             async: false,
     5             url: "http://192.168.1.21:9006/api/ad/GetDiscountHtml",
     6             dataType: "jsonp",
     7             jsonp: "callback",//传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(一般默认为:callback)
     8             success: function (json) {
     9                 alert(5)
    10             },
    11             error: function () {
    12                 alert('fail');
    13             }
    14         });
    15     });
    1     $.getJSON("http://192.168.1.21:9006/api/ad/GetDiscountHtml?jsoncallback=?", function (data) {
    2         alert(1);
    3     });
  • 相关阅读:
    《程序员修炼之道:从小工到专家》读后感2
    Java第五节课总结
    FirstJavaWeb
    Java第四节课总结
    《程序员修炼之道:从小工到专家》读后感1
    Java第三节课总结
    递归回文
    原码、补码和反码
    Java第二节课总结
    C++ STL的容器类型
  • 原文地址:https://www.cnblogs.com/ningyouyou/p/7998972.html
Copyright © 2011-2022 走看看