jquery posting data attribute to the next page

北慕城南 提交于 2021-02-05 09:46:34

问题


I am trying to post data stored in a data-attr to the next page, here is my code

First i add a class and data-attr to all anchor tags like this:

jQuery("a").addClass("wptl_link");
jQuery('a').attr('data-wptl_ip', '<?php echo $_SERVER['REMOTE_ADDR']; ?>');

I have checked my source code when uploaded and this works fine.

I would like to add functionality to each anchor tag, to submit the data-attr of that anchor to the next page.

I am now not quite sure on what to do. I have read into .ajax and .post and not sure what the difference is?

Do i need to do something like the following:

jQuery.ajax({
type: "POST",
url: nextpage.php,
data: { wptl_ip: "<?php echo $_SERVER['REMOTE_ADDR']; ?>"},
success: success,
dataType: dataType
});

回答1:


If I am reading this correctly, you are trying to carry some variable from page to page, when you click an anchor tag.

$.ajax sends the request to another page without moving to the page. $.ajax is used a lot for updating or getting data asynchronously, from other places. Without having to refresh the page.

You can store the data-attr in a sessionStorage variable.

$('body').on('click','a',function(e){
    e.preventDefault();

    var location = $(this).attr('href');
    var data = $(this).attr('data-wptl_ip');

    sessionStorage.setItem('wptl_ip', data);
    location.href= location;
});

then you can access the data info on the next page with

var myData = sessionStorage.getItem('wptl_ip');

This is assuming you want to move to the next page, along with the data.

Posting to a php file to insert in Database:

$('body').on('click','a',function(e){
    e.preventDefault();

    var location = $(this).attr('href');
    var data = $(this).attr('data-wptl_ip');

    $.ajax({
        url: 'somePage.php',
        data: {someData: data} 
    }).done(function(response){
        sessionStorage.setItem('wptl_ip', data);
        location.href= location;
    });


});


来源:https://stackoverflow.com/questions/17842801/jquery-posting-data-attribute-to-the-next-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!