简体   繁体   中英

how to call AJAX function in anchor tag

I'm new to AJAX. i want to call AJAX function when i click a button using onclick() event. This is the AJAX function called by onclick() event

function onclickFunction(aId){
    $.ajax({
        type: "get",
        url: "like_audio",
        data: {
            aId:aId
        },
        success: function (data){
            alert(data);
        },
        error: function (xhr, ajaxOptions, thrownError){

        }
    });
    return false;
}

This is how i'm calling the onclick() event

<a href="" onclick=onclickFunction(id)

Just get the use return inside onclick , which will prevent the reload.

<a href="" onclick="return onclickFunction('id')">a</a>

As an alternative you can use

<a href="javascript:onclickFunction('id')">a</a>
<a href="#" onclick="onclickFunction('theid');">Click Me</a>

Will run the function, and pass it the value 'theid'

In your example, you don't have a comple href, and even if it was right, you might not have an ID value to pass to it. if i do this:

Click Me

I am basically saying, there is a variable called id in the global scope, go find its value and pass it to the function - if there is indeed a variable like that on your page, then it will work, however i don't know if there is.

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