jquery ajax jsonp跨域调用实例代码

复制代码 代码如下:


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApp.WebForm1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<script src="https://www.jb51.net/jquery-1.7.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
    function aa() {
        $.ajax({
            url: "http://localhost:12079/WebForm2.aspx",
            data: "p1=1&p2=2&callback=?",
            type: "post",
            processData: false,
            timeout: 15000,
            dataType: "jsonp",  // not "json" we'll parse
            jsonp: "jsonpcallback",
            success: function(result) {
            alert(result.value1);
            }
        });
    }

</script>
    <title></title>
</head>
<body>
    <form runat="server">
    <div>

    </div>
    </form>
    <p>
        <input type="button" value="button" /></p>
</body>
</html>

服务器端代码

复制代码 代码如下:


 public partial class WebForm2 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

          
         string callback = Request["callback"];
            string v1="1";
            string v2="2";
            string response = "{\"value1\":\"" + v1 + "\",\"value2\":\"" + v2 + "\"}";
            string call = callback + "(" + response + ")";
            Response.Write(call);
            Response.End();
        }
    }

客户端页面和服务器端页面在两个项目中,以便进行跨域调用测试。

跨域实例代码(需要加载jquery,页面为utf-8编码):

复制代码 代码如下:


 <!--拉勾招聘数据-->
  <script type="text/javascript">
   function success_jsonpCallback(data){
    var html = '';
    var pos = '';
    html += '<ul>';
    jQuery.each(data, function(k, v) {
                 if(k<10){
                  pos = '【' + v.city+ '】' + v.positionName + '('+ v.salary +') - '+v.companyName;
      if(pos.length > 20){
       pos = pos.substring(0,19)+'...';
                     }
                     html += '<li><a href="'https://www.jb51.net/+v.posiitonDetailUrl+'" target="_blank" title="【' + v.city+ '】' + v.positionName + '('+ v.salary +') - '+v.companyName+'">'+pos+'</a></li>';
                 }
    });
    html += '</ul><div><a href="https://www.lagou.com/jobs/list_%E5%89%8D%E7%AB%AF%E5%BC%80%E5%8F%91" target="_blank">更多</a></div>';
    jQuery('#lagouData').html(html);
   }

   function getLagouData() {
    jQuery.ajax({
     async:false,
     url: "http://www.lagou.com/join/listW3cplus?kd=%E5%89%8D%E7%AB%AF%E5%BC%80%E5%8F%91",
     type: "GET",
     dataType: "jsonp",
     jsonpCallback: 'success_jsonpCallback',
     contentType: "application/jsonp; charset=utf-8",
     success: function(data) {
      success_jsonpCallback(data);
     }
    });
   }
   getLagouData();
        </script>
      <div></div>

jsonp代码:

复制代码 代码如下:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wdwjyj.html