简体   繁体   English

使用jQuery和Ajax在href中捕获和发送参数

[英]Using jQuery and Ajax to capture and send parameters in href

I've the following HTML link code 我有以下HTML链接代码

<div id="message"></div>
<a href="cats.php?id=60&color=brown&name=kitty" id="petlink">
Click here
</a>

using jQuery and Ajax and On click this link, I would like to send those parameters 使用jQueryAjax并点击此链接,我想发送这些参数

id=60
color=brown
name=kitty

to a file find.php that will catch those parameters using $_GET as 到一个文件find.php将使用$_GET作为捕获这些参数

<?PHP
    $id    = $_GET['id'];     // 60
    $color = $_GET['color']; // brown
    $name  = $_GET['name']; // kitty

// doing some searching in database

echo "yep found it"; // or whatever i would print
?>

and will respond back with whatever (like echo "yep found it" ) that would be shown up in between this div <div id="message"></div> 并将回复任何内容(如echo "yep found it" ),这些内容将显示在div <div id="message"></div>

I've read many tutorials but all was speaking about form data submissions but unfortunately i did not found for such case so any help will really appropriate it. 我已经阅读了很多教程,但所有人都在谈论表单数据提交,但不幸的是我没有找到这样的情况,所以任何帮助都会真正适合它。

To create this you simply need to send an AJAX request from the click event of the a element. 要创建它,您只需要从a元素的click事件发送AJAX请求。 You can retrieve the querystring by reading the src property of the anchor, something like this: 您可以通过读取锚点的src属性来检索查询字符串,如下所示:

$('#petlink').click(function(e) {
  e.preventDefault();

  $.ajax({
    url: 'find.php',
    data: this.src.split('?')[1],
    success: function(response) {
      $('#message').text(response);
    }
  });
});

as rory sad you need to give a click event to your a tag then 因为rory很伤心你需要给你的标签点击事件

$('#petlink').click(function(e) {
e.preventDefault();

 $.ajax({
  type:'POST'
  url: 'find.php&pets=1',
  data: this.href.split('?')[1],
dataType:'json',
  success: function(response) {
    $('#message').text(response);
   }
  });
 });

on your php file just add 在你的PHP文件上添加

if($_GET['pets'] == 1) { if($ _ GET ['pets'] == 1){

 $id    = $_POST['id'];     // 60
  $color = $_POST['color']; // brown
  $name  = $_POST['name']; // kitty
  echo 'pets came';
  exit;

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM