如何使用 jquery 对 php 文件进行 onclick ajax 调用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2496579/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 06:42:30  来源:igfitidea点击:

How to do an onclick ajax call to a php file, with jquery?

phpjqueryajaxonclick

提问by Dustin Laine

I have a link, which links to domain.com , when a person clicks, I want it to do an ajax call to counter.php and post 2 variables to it, so it can add 1 to the views for that link.

我有一个链接到 domain.com 的链接,当一个人点击时,我希望它对 counter.php 进行 ajax 调用并向其发布 2 个变量,因此它可以为该链接的视图添加 1。

I have a link:

我有一个链接:

<a href="http://www.domain.com" onClick="addHit('12345', '1')" rel="nofollow" target="_blank">Link Title</a>

How would I do this with jquery?

我将如何用 jquery 做到这一点?

EDIT:

编辑:

I tried something like this

我试过这样的事情

function addHit(str, partNumber){
$.get("counter.php", { version: str, part: partNumber })                
}

It seems to work, but in firebug, the request never completes... it just does that "working..." animation. counter.php echos out some text when its done (doesnt need to show up anywhere).

它似乎工作,但在萤火虫中,请求永远不会完成......它只是做那个“工作......”动画。counter.php 完成后会回显一些文本(不需要出现在任何地方)。

回答by Dustin Laine

From the jQuery documentation: http://api.jquery.com/jQuery.ajax/

来自 jQuery 文档:http: //api.jquery.com/jQuery.ajax/

function addHit(data1, data2)
{
    $.ajax({
       type: "POST",
       url: "http://domain.com/counter.php",
       data: "var1=data1&var2=data2",
       success: function(msg){
         alert( "Data Saved: " + msg ); //Anything you want
       }
     });
}

回答by lemon

You need to add a callback on success

您需要在成功时添加回调

function addHit(str, partNumber){
$.get(
"counter.php", 
{ 
 version: str, 
 part: partNumber 
},
function(data){
   alert("Data Loaded: " + data);
 })
)};

回答by Nick Craver

In the case of an anchor, you're leaving the page, so firebug's going to show some weird behavior here as it thinks execution would stop. Unless you're also preventing the default event behavior of the anchor...you're leaving the page and the request (in firebug's view) is discarded.

在锚点的情况下,您将离开页面,因此 firebug 将在此处显示一些奇怪的行为,因为它认为执行将停止。除非您还阻止锚点的默认事件行为……否则您将离开页面并且请求(在萤火虫的视图中)被丢弃。