【问题标题】:cross domain ajax request fails in android deviceandroid设备中的跨域ajax请求失败
【发布时间】:2016-07-03 12:46:42
【问题描述】:

我有一个非常基本的 jqm/phonegap 应用程序

这是我的html

<html>
<head>
<title>jQuery Mobile Web App</title>
<link href="jquery-mobile/jquery.mobile-1.0.min.css" rel="stylesheet" type="text/css"/>
<link href="style.css" rel="stylesheet" type="text/css">
<script src="jquery-mobile/jquery-1.6.4.min.js" type="text/javascript"></script>
<script src="jquery-mobile/jquery.mobile-1.0.min.js" type="text/javascript"></script>

</head>
<body >
<div data-role="page" id="home"  >
  <div data-role="header">
    <h1>p</h1>
  </div>
  <div data-role="content" style="text-align:right" id="c1">


  </div>
  </div>
</div>
</div>

这是我的 js 代码,它位于 html 代码的主体中

 <script>

    function get_news_list(id , link_ , refresh_ ){

        jQuery.support.cors = true;

        $.ajax({
        url :  link_ ,  
        success:function(data){
            $('#c1').html(data);

                        } ,
        error : function(data) {

            alert(data.toSource);

            }
        });
    }

  get_news_list('latest' , 'http://pnup.ir/?feed=json' , refresh_);

    </script>

当我将它作为网页运行时,我得到了

此警报 如果是火狐

function toSource() {
    [native code]
}

镀铬

  undefined 

我认为这没问题,因为它是一个跨域 ajax 请求,它在网络浏览器中失败(尽管在 firebug 中它的状态是好的 200 它只是没有返回任何响应) 但是当我在我的 android 设备上测试它时,我得到了相同的 undefined 。我认为跨域 ajax 请求一旦我在 android 设备中运行它作为应用程序就没有问题?

我错过了什么吗?我应该使用 jsonp 吗?它是一个 wordpress 网站和 json feed 插件,它的 feed 可以在 json 中使用,但是获取 jsonp feed 将是一场噩梦......至少我不知道如何!

【问题讨论】:

    标签: ajax wordpress jquery cordova jquery-mobile


    【解决方案1】:

    我最近在我的一个 phonegap + jquerymobile 项目中实现了 jsonp,我遇到了同样的问题,但我使用 asp.net 作为我的服务

    像下面这样调用服务对我有用,您只需添加 ?fnCallBack=?在网址的末尾

    $.ajax({        
            url : link_+'?fnCallBack=?',
            contentType : "application/json; charset=utf-8",
            dataType : "json",
            jsonp : 'json',
            cache : false,
            success : function(result) {
                if (result != 'Error') {
                    var valX = JSON.stringify(result);
                    valX = JSON.parse(valX);
                } else {
                    navigator.notification.alert("An error occured, Please try later");
                }
            }
        });
    

    在服务器端,当您发送 json 响应时,只需像这样添加 fnCallBack

            string jsoncallback = context.Request["fnCallBack"];
            context.Response.Write(string.Format("{0}({1})", jsoncallback,jsonData));
    

    这样我解决了我的跨域问题,所以希望你能从中得到线索

    【讨论】:

      猜你喜欢
      • 2015-01-28
      • 2014-11-22
      • 2013-08-09
      • 1970-01-01
      • 1970-01-01
      • 2017-12-27
      • 2014-03-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多