2014-05-17 143 views
0

I need to display a query via AJAX and to be able to do that, i have to match the ID of the product. Thus i thought of performing a POST method via AJAX to allow the execution of the query.通过<a href> - PHP

Now i would like to do a trigger function for the AJAX such that the information will be shown on the page itself instead of being redirect to another page. How do i go about doing it ? I have added tried various place to add the Onclick function, however nothing seems to work.

Any suggestion ?

Thanks

echo '<a onclick="showUser('.$row['ID'].')" method = "POST" action= "viewComments.php">Show Comments</a>'; 

<script> 
function showUser(str) { 
    if (str=="") { 
    document.getElementById("txtHint").innerHTML=""; 
    return; 
    } 
    if (window.XMLHttpRequest) { 
    // code for IE7+, Firefox, Chrome, Opera, Safari 
    xmlhttp=new XMLHttpRequest(); 
    } else { // code for IE6, IE5 
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
    } 
    xmlhttp.onreadystatechange=function() { 
    if (xmlhttp.readyState==4 && xmlhttp.status==200) { 
     document.getElementById("txtHint").innerHTML=xmlhttp.responseText; 
    } 
    } 
    xmlhttp.open("Post","viewComments.php?q="+str,true); 
    xmlhttp.send(); 
} 
</script> 
+0

你有一个函数,需要一个参数:'showUser( str)',但是当你调用它时,你没有提供该参数的值。 – IMSoP

回答

1

Remove the 'href=""' from your links. This is how they should look:

<a Onclick="showUser()" >Show Comments</a> 

Hope this helps! :)

Edit: This is how I would call "showUser()" with an ID:

echo '<a onclick="showUser('.$row['ID'].')" >Show Comments</a>'; 
+0

Svensson。谢谢它确实有帮助。我是否也可以与您核对,这是我发布我的价值(ID)的正确方法吗? –

+0

你是什么意思?您在隐藏字段中拥有的ID? –

+0

Yeap。那是一个。你怎么看 ? –

-1

Try this one.

<a id="showUser">Show Comments</a> 

$('#showUser').click(function(){ 
    //your ajax code goes here 
    return false; 
}); 
+0

这需要jQuery。他使用常规的JavaScript。 –

0

I just do not like those onClick() events in the html. It is also not good practice (see Why is using onClick() in HTML a bad practice?触发AJAX功能)

这将只是更好的事件绑定到HTML元素在你的JavaScript不是你的HTML。 像这样:

HTML:

<a href="http://echo.jsontest.com/key/value/one/gotIt" id="myLink" >Show Comments</a> 

的Javascript:

function addEventListener(el, eventName, handler) { 
    if (el.addEventListener) { 
    el.addEventListener(eventName, handler); 
    } else { 
    el.attachEvent('on' + eventName, function(){ 
     handler.call(el); 
    }); 
    } 
} 

var el = document.getElementById('myLink'); 
addEventListener(el, 'click', showUser); 

演示:http://jsfiddle.net/dgrCw/1/

只是我的两分钱......

相关问题