weixin_33711647 2017-06-02 18:42 采纳率: 0%
浏览 36

Ajax网址被覆盖

I am making an AJAX request onchange from a rails app. The function is a very simple PUT request:

function quantityChange(id, val) {
    $.ajax({
        url: 'cart_items/' + id,
        method: "PUT",
        data: {quantity: val},
        success: function() {}
    })
}

My issue is the URL that is being called by the request is http://localhost:3004/ and not http://localhost:3004/cart_items/:id.

I am using jQuery 1.9.1 and have tested the snippet in JSBin. Everything works as expected there but in the Rails app it tries to call the root hostname. If I change the url to cart_items + id without the forward slash the concatenation and url come out almost correct http:localhost:3004/cart_items:id minus the forward slash that is needed.

I do not understand why the application is defaulting to the root hostname when providing ajax with this url.

Error in console

  • 写回答

1条回答 默认 最新

  • weixin_33704591 2017-06-02 19:11
    关注

    The issue was I needed to set my CSRF Token. Since I did not have one the request was being redirected to the root hostname.

    function quantityChange(id, val) {
        debugger;
        $.ajax({
            url: 'cart_items/' + id,
            type: "PUT",
            data: {quantity: val},
            beforeSend: function(xhr){xhr.setRequestHeader('X-CSRF-Token', 'token');},
            success: function() {}
        })
    }
    
    评论

报告相同问题?