简体   繁体   中英

Jquery .ajax passing msg to click event

I'm developing a small application in javascript using jquery but i've a small problem.

i've this function

function cercahq(urlvalue) {
    $.ajax({
    type: "POST",
    url: "data.php",
    data: "do=urlget&url=" + urlvalue,
    dataType: "html",
    success: function(msg) {
        var data = eval('(' + msg + ')');
        $("#searchbar").css({'background-color': '#C33'});
        // creates element
                var insertform = document.createElement('form');
        insertform.id = "insertform";
        var insertbutton = document.createElement('button');
        var insertbuttonlabel = document.createTextNode('Insert');
        insertbutton.appendChild(insertbuttonlabel);
        insertform.appendChild(insertbutton);
        $("#searchbar").append(insertform);

       $(insertbutton).click(function(event, data) {
             event.preventDefault();
             alert(data.title);
        });

        stampa(msg)
        },
    error: function()
      {
        alert("Error");
      }
});

}

This function gets json data from a php script and pass it to a function (stampa) that evals it and print it in the page, but i need to create a button outside the stampa function that tells me a value from the json... So inside the success event i've insered another eval to grab the ajax msg and create the variable data that should be passed to a button element that i've created inside a form called insertform.

The point is: how to pass the "data" variable to the click function from an element created inside an ajax request success function?

The 'data' variable should be accesible inside click function through closure, no need to pass it there. By passing it as parameter you override it as closure with 'undefined' value. So just remove it from parameters:

 $(insertbutton).click(function(event) {
         event.preventDefault();
         alert(data.title);
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM