通过单击链接发送 AJAX 请求而不重定向用户 [英] Send AJAX request by clicking a link without redirecting user

查看:33
本文介绍了通过单击链接发送 AJAX 请求而不重定向用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Web 应用程序,其中包含许多不同的项目,这些项目是从 MySQL 表生成的.当用户滚动浏览它时,我希望他们能够单击项目旁边的链接,该链接会将请求插入到 MySQL 数据库中.通常,我会通过创建一个 PHP 页面(无论如何我都会这样做)来获取项目名称 &使用 $_GET 方法从 URI 获取用户 ID &将其插入表中.但是,在这种情况下,我不希望用户被重定向到远离他们所在的任何地方.我只是希望链接发送请求,并且可能在成功后显示一条小消息.

I have a web application which features a bunch of different items, which are generated from a MySQL table. As users scroll through it, I want them to be able to click a link next to the item which will insert the request into a MySQL database. Normally, I’d do this by creating a PHP page (which I will do anyways) that grabs the item name & user id from the URI using the $_GET method & inserts it into the table. However, in this case, I don’t want the users to be redirected away from wherever they are. I just want the link to send off the request, and maybe display a small message after it is successful.

我认为 jQuery/AJAX 最适合这个,但由于我不太熟悉它,我不知道该怎么做.任何提示表示赞赏!

I figured jQuery/AJAX would be best for this, but as I’m not too familiar with it, I’m not sure what to do. Any tips are appreciated!

推荐答案

你必须做类似的事情

$('.classofyourlink').click(function(e){
  e.preventDefault();//in this way you have no redirect
  $.post(...);//Make the ajax call
});

通过这种方式,用户通过点击链接而不重定向来进行ajax调用.以下是 $.post

in this way the user makes an ajax call by clicking a link without redirecting. Here are the docs for $.post

编辑 - 在你的情况下将值传递给 jQuery,你应该做类似的事情

EDIT - to pass the value to jQuery in your case you should do something like

$('.order_this').click(function(e){
  e.preventDefault();//in this way you have no redirect
  var valueToPass = $(this).text();
  var url = "url/to/post/";
  $.post(url, { data: valueToPass }, function(data){...} );//Make the ajax call
});

这篇关于通过单击链接发送 AJAX 请求而不重定向用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆