简体   繁体   中英

How to use callback function in ajax when clicking on a link

I am using jquery ajax when clicking on a link but i want to pass a usedefined function name from that link so that when i get results from ajax it should callback to the function i have passed . i am using this

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script type="text/javascript">
var call_me = function(data){
alert(data);
};
var  getmsg = function (val,callback) {
// alert(val+call_me);
$.ajax({
url : "send.php",
type : "post",
data : {value:val},
success : callback
})
}
</script>
<a href="#" onclick="getmsg($(this).html(),'call_me');">wewewe</a>

"call_me" is passed as a string at js at Question, try passing function name to getmsg

function call_me(data){alert(data)} 

onclick="getmsg($(this).html(), call_me);"

alternatively,

$("a[href=#]").click(function() {
  getmsg(this.innerHTML, call_me)
})

Function is just another object in javascript, so instead of passing function name, pass function itself:

<a href="#" onclick="getmsg($(this).html(), call_me);">wewewe</a>

var getmsg = function (val,callback) {
    $.ajax({
        url : "send.php",
        type : "post",
        data : {value:val},
        success : callback
    });
}

I find mixing inline javascript in html with jQuery a very bad idea. You can achieve the same behaviour by using properly the library and keeping your html intact

<a href="#" class="the-link-element">wewewe</a>

$("a.the-link-element").on("click", function(e){
    // or .html()/.innerHtml() is not clear what you want
    getmsg($(e.target).text(), call_me);
});

var call_me = function(data){
    alert(data);
};

var  getmsg = function (val,callback) {
// alert(val+call_me);
        $.ajax({
        url : "send.php",
        type : "post",
        data : {value:val},
        success : callback
    })
}

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