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

时间:2015-01-23 05:18:54

标签: javascript php jquery ajax

我正在用PHP创建一个在线考试应用程序,但是我遇到了AJAX调用问题。

当我点击右侧的其中一个按钮时,我希望使用AJAX调用获取问题(并用于填充div)。这些按钮不是静态的;它们是在服务器上生成的(使用PHP)。

Here is interface of front end

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

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

按钮应该调用这样的函数:

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

请建议一个可以使这项工作的AJAX电话

3 个答案:

答案 0 :(得分:1)

你这样做是错误的。 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.
});

答案 1 :(得分:1)

我建议你有这样的东西来生成按钮:

<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);
  });
});

答案 2 :(得分:1)

<强> 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");
     }
 });

})

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

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

成功是jQuery在PHP文件调用成功后会做的事情。

有关ajax的更多信息here

<强> PHP

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