如何在jQuery .load()函数中传递Accept标头

时间:2022-12-08 19:52:56

How to pass Accept header in jQuery .load() function as It need to be passed.

如何在jQuery .load()函数中传递Accept标头,因为它需要传递。

2 个解决方案

#1


0  

As mentioned in an earlier answer by Jon, load can't do it by itself. I prefer to use the headers option on the ajax method rather than beforeSend:

正如乔恩先前的回答中所提到的,加载不能单独完成。我更喜欢在ajax方法而不是beforeSend上使用headers选项:

$.ajax({
    url: "http//example.com",
    headers: {
        Accept: "application/whatever" // Use the actual type you need.
    },
    success: function (data) {
        // Put the data into the element you care about.
        $("#foo").html(data);
    },
    error: function (jqXHR) {
        // Put whatever you need to do if the query fails here.
    }
});

The end result is the same but if I like saving keystrokes.

最终结果是一样的,但如果我喜欢保存击键。

#2


6  

You need to utilize the beforeSend parameter in the ajax method, since load does not expose this functionality:

您需要在ajax方法中使用beforeSend参数,因为load不会公开此功能:

$.ajax({
    url: "http://www.server.com/",
    beforeSend: function(jqXHR, settings) {
        jqXHR.setRequestHeader("Accept", "application/json");
    },
    // You need to manually do the equivalent of "load" here
    success: function(result) {
        $("selector").html(result);
    }
});

#1


0  

As mentioned in an earlier answer by Jon, load can't do it by itself. I prefer to use the headers option on the ajax method rather than beforeSend:

正如乔恩先前的回答中所提到的,加载不能单独完成。我更喜欢在ajax方法而不是beforeSend上使用headers选项:

$.ajax({
    url: "http//example.com",
    headers: {
        Accept: "application/whatever" // Use the actual type you need.
    },
    success: function (data) {
        // Put the data into the element you care about.
        $("#foo").html(data);
    },
    error: function (jqXHR) {
        // Put whatever you need to do if the query fails here.
    }
});

The end result is the same but if I like saving keystrokes.

最终结果是一样的,但如果我喜欢保存击键。

#2


6  

You need to utilize the beforeSend parameter in the ajax method, since load does not expose this functionality:

您需要在ajax方法中使用beforeSend参数,因为load不会公开此功能:

$.ajax({
    url: "http://www.server.com/",
    beforeSend: function(jqXHR, settings) {
        jqXHR.setRequestHeader("Accept", "application/json");
    },
    // You need to manually do the equivalent of "load" here
    success: function(result) {
        $("selector").html(result);
    }
});