繁体   English   中英

我如何在jQuery的ajax函数调用中发送参数

[英]How do i send parameter in ajax function call in jquery

我正在用PHP创建一个在线考试应用程序,而AJAX调用遇到了麻烦。

我希望在单击右侧的按钮之一时使用AJAX调用来提取问题(并用于填充div)。 这些按钮不是静态的。 它们是在服务器上生成的(使用PHP)。

这是前端的接口

我正在寻找这样的AJAX调用:

functionname=myfunction(some_id){
ajax code
success: 
html to question output div
}

该按钮应调用如下函数:

<button class="abc" onclick="myfunction(<?php echo $question->q_id ?>)">

请提出一个AJAX调用,以使其正常工作

您做错了方法。 jQuery具有内置的运算符,可以处理类似这样的事情。

首先,当您生成按钮时,建议您像这样创建它们:

<button id="abc" data-question-id="<?php echo $question->q_id; ?>">

现在在按钮上创建一个监听器/绑定:

jQuery(document).on('click', 'button#abc', function(e){
    e.preventDefault();
    var q_id = jQuery(this).data('question-id'); // the id

    // run the ajax here.
});

我建议您使用类似的方法来生成按钮:

<button class="question" data-qid="<?php echo $question->q_id ?>">

您的事件侦听器将如下所示:

$( "button.question" ).click(function(e) {
  var button = $(e.target);
  var questionID = button.data('qid');
  var url = "http://somewhere.com";
  $.ajax({ method: "GET", url: url, success: function(data) {
    $("div#question-container").html(data);
  });
});

的HTML

<button class="abc" questionId="<?php echo $question->q_id ?>">

脚本

$('.abc').click(function () {
 var qID = $(this).attr('questionId');
 $.ajax({
     type: "POST",
     url: "questions.php", //Your required php page
     data: "id=" + qID, //pass your required data here
     success: function (response) { //You obtain the response that you echo from your controller
         $('#Listbox').html(response); //The response is being printed inside the Listbox div that should have in your html page. Here you will have the content of $questions variable available
     },
     error: function () {
         alert("Failed to get the members");
     }
 });

})

type变量告诉浏览器您要对PHP文档进行调用的类型。 您可以在此处选择GET或POST,就像处理表单一样。

数据是将传递到您的表单上的信息。

如果成功调用PHP文件,则jQuery将执行成功。

更多关于ajax的信息

的PHP

 $id = gethostbyname($_POST['id']);
 //$questions= query to get the data from the database based on id
return $questions;

暂无
暂无

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

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