duaj39673
2016-03-17 18:58
浏览 94

如何在单击链接时在ajax中使用回调函数

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>

图片转代码服务由CSDN问答提供 功能建议

我在点击链接时使用jquery ajax但我想从该链接传递一个usedefined函数名称,以便 当我从ajax得到结果时,它应该回调我已经通过的函数。 我正在使用

 &lt; script src =“https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js”  &gt;&lt; / script&gt; 
&lt; script type =“text / javascript”&gt; 
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},
成功:callback 
}  )
} 
&lt; / script&gt; 
&lt; a href =“#”onclick =“getmsg($(this).html(),'call_me');”&gt; wewewe&lt; / a&gt; 
   
 
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dtgr3392 2016-03-17 19:04
    已采纳

    "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)
    })
    
    打赏 评论
  • dpkrh2444 2016-03-17 19:01

    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
        });
    }
    
    打赏 评论
  • douyingtai6662 2016-03-17 19:27

    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
        })
    }
    
    打赏 评论

相关推荐 更多相似问题