How to run jQuery onClick? Need to pass a variable to run .ajax

99封情书 提交于 2019-12-08 12:27:11

问题


I'm trying to run .ajax and insert a data element from the onClick of an item from the page. Whats the best way to do this?

Something like this:

function grabinfo(foo){

      $.ajax({
      url: "infospitter.php",
      method: "GET",
      data: "id="+foo,
      success: function(html){
       $(#showstuff).html(html);
       }
      });

}

  <input onClick="javascript:grabinfo(18343)" />
// and on page each item will have this button input

回答1:


It's usually best to keep your javascript unobtrusive, and out of the DOM.

<input type="button" value="18434"/>

In your javascript file:

$('input[type=button]').click(function(){
    $.ajax({
        url: 'infospitter.php',
        method: 'GET',
        data: 'id=' + $(this).attr('value'),
        success: function(returnData){
            // Do something with returnData
        }
    });
});



回答2:


Remove the "javascript:" from your onclick attribute. That's only needed when running code outside a javascript event attribute.



来源:https://stackoverflow.com/questions/2495692/how-to-run-jquery-onclick-need-to-pass-a-variable-to-run-ajax

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