简体   繁体   中英

$.ajax calls working, but backbone fetch and save are not working

I have a backbone app where any $.ajax() call I make to the PHP API works great and returns successful on a GET or POST request. However, when I try a model.fetch() or model.save() call (using the same endpoint), I am returned with:

XMLHttpRequest cannot load http://xyz.com.
Origin http://localhost is not allowed by Access-Control-Allow-Origin.

I know that's not much to go off of, but would there be a reason that backbone's ajax calls would be returning with errors, but when converted to just plain ajax calls, they are successful?

The headers in my PHP-based API on the server are:

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true"); 
header('Access-Control-Allow-Headers: origin, content-type, accept');
header('Access-Control-Allow-Methods: OPTIONS, POST, GET, DELETE, PUT');
header('Access-Control-Max-Age: 86400'); 

Backbone is using Backbone.sync method to do ajax. It is doing same jquery.ajax with some default settings. This is the source code for Backbone.sync. You can match backbone's ajax setting with your ajax.

I am not sure about your approach. I did using fetch in the below manner. it worked fine for me. This might help you.

When you call .fetch, the model will trigger a request event, and when you receive it, parse it and set it to the model, the model will trigger a sync event.

var UserModel = Backbone.Model.extend({ url:' http://api.geonames.org/astergdemJSON?formatted=true&lat=50.01&lng=10.2&username=demo&style=full ' });

var MyView = Backbone.View.extend({
    initialize: function() {
        this.model = new UserModel();
        this.listenTo(this.model,'sync', this.render);
        this.model.fetch({success:this.success,error:this.error});
    },
    render: function() {
        console.log('do awesome stuff here'+this.model.toJSON());
    },
    success:function(data){
        console.log(data.attributes.status);
    },
    error:function(data){
        console.log('error'+data.attributes.status)
    }
});

var view = new MyView();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM