jQuery中的.html()从PHP脚本中获取回显

时间:2012-06-20 19:15:32

标签: jquery ajax

我有这个:

  $(document).ready(function() {
    $("input[type=button]").click(function () {
        $("#test").html("W3Schools");
        alert("Would submit: " + $(this).siblings("input[type=text]").val());
        $.ajax({ url: "index.php",
        data: {action: $(this).siblings("input[type=text]").val()},
        type: 'post'
        });
    });
});

'W3Schools'显然只是填充物,我在我的php脚本中有一个名为'generateHTML()'的函数,我想代替'W3Schools'。我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

无论您在何处定义该功能,请使用 echo 响应,而不是返回响应。

所以每当你调用$ .ajax函数时,它都会给出你可以在html中使用的响应。

PHP功能:

function generateHTML(){
 // code
  echo $response;
}

JS:

$(document).ready(function() {
    $("input[type=button]").click(function () {
        $("#test").html("W3Schools");
        alert("Would submit: " + $(this).siblings("input[type=text]").val());
        $.ajax({ url: "index.php",
        data: {action: $(this).siblings("input[type=text]").val()},
        type: 'post',
        success: function(response){
              $("#test").html(response); // will overwrite the previous HTML of test element
            }
        });
    });
});