覆盖Backbone.ajax方法以使用cordovaHTTP

问题描述 投票:0回答:1

我正在开发一个使用Backbone JS的phonegap应用程序。在ajax调用期间,标头包含:

“原产地”: “文件://”

服务器不支持。我试图将Origin标头设置为null,但在chrome中不允许。

Backbone.ajax = function() {  
    arguments[0].headers = {
        'Accept': "application/json",
        'Origin': "null"
    };
    return Backbone.$.ajax.apply(Backbone.$, arguments);      
  };

哪个抛出错误:

拒绝设置不安全的标题“Origin”

只有我可以想到解决这个问题的方法是使用cordovaHttp插件。但我无法弄清楚如何覆盖Backbone.ajax以使用cordovHTTP。

链接到cordova插件:https://github.com/silkimen/cordova-plugin-advanced-http

虽然这与CORS有关,但我的问题是使用cordovaHttpPlugin来覆盖Backbone ajax方法。

javascript ajax cordova backbone.js phonegap
1个回答
0
投票

有用:

function isPhoneGap() {
    return (window.cordova || window.PhoneGap || window.phonegap) 
    && /^file:\/{3}[^\/]/i.test(window.location.href) 
    && /ios|iphone|ipod|ipad|android/i.test(navigator.userAgent);
}

Backbone.sync = function( method, model, options ) {

        if(method == "read"){

            if(isPhoneGap()){
                cordova.plugin.http.get(model.url, {}, { Origin: "null" }, function(response) {
                    // prints 200
                    console.log(response.status);
                    try {
                        options.success(JSON.parse(response.data));
                    } catch(e) {
                        console.error("JSON parsing error");
                    }
                }, function(response) {
                    console.log(response.status);
                    console.log(response.error);
                });
            }else{

                $.ajax({
                    type : 'GET',
                    url : model.url,
                    dataType : 'json',
                    success : function(data) {
                        console.log(data);
                        if(model instanceof Backbone.Collection){
                            model.reset(JSON.parse(JSON.stringify(data)));
                        }else{
                            model.set(JSON.parse(JSON.stringify(data)));
                        }
                    }
                });
            }
        }
  }
© www.soinside.com 2019 - 2024. All rights reserved.