问题
The basic kendo auto complete example shows a setup where matched search results are fetched through an Ajax request. The ajax loading works fine if the requested resource is on the same domain, but I was wondering if there is support for configuring the underlying ajax requests to support CORS. Is there a way to pass in Ajax options like you normally would do if you were using $.ajax({})
directly.
$("#products").kendoAutoComplete({
dataTextField: "ProductName",
filter: "contains",
minLength: 3,
dataSource: {
type: "odata",
serverFiltering: true,
serverPaging: true,
pageSize: 20,
transport: {
read: "http://demos.kendoui.com/service/Northwind.svc/Products"
}
}
});
});
I basically want the same granular control over the request as in a regular JQuery Ajax request (example bellow):
jQuery.ajax({
url: 'some url',
data: {id:id},
contentType: 'application/json',
type: "Get",
xhrFields: {
withCredentials: true
},
crossDomain: true
})
回答1:
The solution is to assign the read property to a method that wraps the ajax call like so:
$("#search").kendoAutoComplete({
dataTextField: "Name",
minLength: 1,
dataSource: {
type: "json",
serverFiltering: true,
transport: {
read:
function(options) {
$.ajax({
url: "someUrl",
contentType: 'application/json',
data: { text: options.data.filter.filters[0].value },
type: "Get",
xhrFields: {
withCredentials: true
},
crossDomain: true,
success: function (result) {
options.success(result);
}
});
}
}
}
}
});
This gives you the ability to replace the default ajax behavior.
回答2:
You can set user on beforeSend
method;
$("#products").kendoAutoComplete({
dataTextField: "ProductName",
filter: "contains",
minLength: 3,
dataSource: {
type: "odata",
serverFiltering: true,
serverPaging: true,
pageSize: 20,
transport: {
read: {
url: "http://demos.kendoui.com/service/Northwind.svc/Products",
type: 'POST',
beforeSend: function(req) {
req.setRequestHeader('Auth', your_token);
}
}
}
}
});
});
回答3:
You can achieve it by setting withCredentials to true for the property "xhrFields" of reader as below for the data source definition.
dataSource: {
transport: {
read: {
xhrFields: {
withCredentials: true
},
url: serviceURL
}
}
}
Make sure you have already set SupportsCredentials = true in the cors settings in the target server.
Hope this helps
来源:https://stackoverflow.com/questions/21169823/configure-ajax-request-made-by-kendo-to-support-cross-domain-ajax-request