콜백 함수에서 jQuery Ajax 요청 URL에 액세스하다
jQuery로 Ajax 요청을 했을 때 요청한 URL을 볼 수 있는 방법이 있나요?
예.,
var some_data_object = { ...all sorts of junk... }
$.get('/someurl.php',some_data_object, function(data, textStatus, jqXHR) {
var real_url = ? # <-- How do I get this
})
jQuery가 실제로 요청을 작성하기 위해 사용한 URL에 액세스하려면 어떻게 해야 합니까?아마도 몇 가지 방법/속성jqHXR
문서에서는 찾을 수 없었습니다.
감사해요.
성공 방법의 중단점을 설정한 후 시청합니다.
this.url
는 요구의 실제 URL 입니다.
다음으로 생각할 수 있는 해결책을 제시하겠습니다.
- beforeSend callback 함수를 구현하여 서버로 전송하기 전에 Ajax 콜을 포착합니다.
- URL 및 데이터 저장
생성한 오류 메시지로 보고합니다.
var url = ""; $.ajax({ url: "/Product/AddInventoryCount", data: { productId: productId, trxDate: trxDate, description: description, reference: reference, qtyInCount: qtyInCount }, //encodeURIComponent(productName) type: 'POST', cache: false, beforeSend: function (jqXHR, settings) { url = settings.url + "?" + settings.data; }, success: function (r) { //Whatever }, error: function (jqXHR, textStatus, errorThrown) { handleError(jqXHR, textStatus, errorThrown, url); } }); function handleError(jqXHR, textStatus, errorThrown, url) { //Whatever }
사용.$.ajaxPrefilter
:
// Make sure we can access the original request URL from any jqXHR objects
$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
jqXHR.originalRequestOptions = originalOptions;
});
$.get(
'http://www.asdf.asdf'
).fail(function(jqXHR){
console.log(jqXHR.originalRequestOptions);
// -> Object {url: "http://www.asdf.asdf", type: "get", dataType: undefined, data: undefined, success: undefined}
});
http://api.jquery.com/jQuery.ajaxPrefilter/
ajaxSend 글로벌핸들러(http://api.jquery.com/ajaxSend/)는 설정 파라미터에 URL을 나타냅니다.xhr 객체에서 url로의 매핑을 ajaxSend 콜백에 저장한 후 정상적으로 콜백에 제공된 xhr 객체를 조회할 수 있습니다.
var mappings = {};
$.ajaxSend(function(event, xhr, settings) {
mappings[xhr] = settings.url;
});
$.ajax({
url: "http://test.com",
success: function(data, textStatus, xhr) {
console.log("url = ", mappings[xhr]);
delete mappings[xhr];
}
});
이것은 각 $.ajax() 개체를 변경할 필요가 없다는 장점이 있습니다.
참고로, Airbai의 코멘트(답변 내에서는 코멘트 할 수 없습니다)에 덧붙여, 자신의 데이터를 콜에 추가해 콜백내에서 취득할 수 있습니다.이렇게 하면 URL을 해석할 필요가 없습니다.
이 예에서는 JSONP 요구 변수를 추가했습니다.user_id
(jQuery 3.2에서 테스트):
var request = $.ajax({
dataType: "json",
url: "http://example.com/user/" + id + "/tasks?callback=?",
user_id: id,
success: function(data) {
console.log('Success!');
console.log("User ID: " + this.user_id);
},
timeout: 2000
}).fail(function() {
console.log('Fail!');
console.log("User ID: " + this.user_id);
});
문서에서도 찾을 수 없었어요jqXHR 오브젝트에 "프록시" 래퍼로 추가할 수 있습니다.
아직 테스트하지 않았기 때문에 전화 주세요.$.param()
를 참조해 주세요.http://api.jquery.com/jQuery.param/ 를 참조해 주세요.
var myGet = function(url, data, success) {
$.get(url, data, function(data, textStatus, jqXHR) {
jqXHR.origUrl = url; // may need to concat $.param(data) here
success(data, textStatus, jqXHR);
});
}
사용방법:
var some_data_object = { ...all sorts of junk... }
myGet('/someurl.php',some_data_object, function(data, textStatus, jqXHR) {
var real_url = jqXHR.origUrl;
})
언급URL : https://stackoverflow.com/questions/5468312/access-the-url-of-an-jquery-ajax-request-in-the-callback-function
'programing' 카테고리의 다른 글
TypeScript의 public static const (0) | 2023.04.05 |
---|---|
React 컴포넌트에서 Markdown을 렌더링하려면 어떻게 해야 합니까? (0) | 2023.04.05 |
루트 네브링크는 항상 액티브클래스 React Router Domain을 가져옵니다. (0) | 2023.04.05 |
AngularJs: $routeProvider를 사용하여 컨트롤러를 두 번 호출합니다. (0) | 2023.04.05 |
CSS 또는 jQuery에서 단어 사이의 줄 바꿈과 구두점을 방지하려면 어떻게 해야 합니까? (0) | 2023.04.05 |