Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
263 views
in Technique[技术] by (71.8m points)

jquery - Getting the response from AJAX request and inserting it into outgoing link

All outgoing traffic from my site gets entered into a database. I want to then put the ID of the inserted row into the outgoing link href. The URLs have a variable in them called $id like example.com?id=$id. I want to replace that $id with the inserted row's id like example.com?id=114.

I'm inserting into the db fine but I have a hard time from there. I've found many similar questions to mine but they don't seem to fit exactly. How can I get the value from the "process" function so I can append it to the link?

So far this is what I have. Any advice is welcome!

jQuery('a[href^="http"]').not('[href*="' + window.location.host + '"]').on('click', function(e) {
    jQuery.ajax({
      data: {
        action: 'the_ajax_hook',
        source: jQuery.cookie('source'),
        destination: jQuery(this).attr("href"),
        },
      type: 'post',
      url: ajax_object.ajaxurl,
      success: function(data) {
        process(data);
      }
    });

    function process(data) {
      //?????
    }
    jQuery(this).attr('href',jQuery(this).attr('href').replace('$id',id));

    //for testing
    console.log(jQuery(this).attr('href'));
    e.preventDefault();
  });
});
question from:https://stackoverflow.com/questions/65894907/getting-the-response-from-ajax-request-and-inserting-it-into-outgoing-link

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Updating the href doesn't work, because the callback function operates asynchronously.

Instead, assign to window.location to redirect to the new URL instead of performing the default action of the link.

jQuery('a[href^="http"]').not('[href*="' + window.location.host + '"]').on('click', function(e) {
  e.preventDefault(); // don't follow the link automatically
  let url = jQuery(this).attr("href");
  jQuery.ajax({
    data: {
      action: 'the_ajax_hook',
      source: jQuery.cookie('source'),
      destination: url,
    },
    type: 'post',
    url: ajax_object.ajaxurl,
    success: function(data) {
      process(url, data);
    }
  });
});

function process(url, data) {
  let target = url.replace('$id', data);
  window.location = target;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...