programing

콜백 함수에서 jQuery Ajax 요청 URL에 액세스하다

telecom 2023. 4. 5. 21:17
반응형

콜백 함수에서 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 입니다.

다음으로 생각할 수 있는 해결책을 제시하겠습니다.

  1. beforeSend callback 함수를 구현하여 서버로 전송하기 전에 Ajax 을 포착합니다.
  2. URL 및 데이터 저장
  3. 생성한 오류 메시지로 보고합니다.

    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

반응형