如何将php变量传递给jquery AJAX?

I have started learning jquery AJAX. I have run into a problem, and was wondering if you guys could help me. I am trying to pass a php variable back to jquery, but it displays as [object Object]. I will be posting my code below.

index.html:

<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
    $("button").click(function() {
        $("p").text($.get("return.php"));
    });
});
</script>
</head>

<body>
<p>This is a test!</p>
<button>Click Here</button>
</body>
</html>

return.php:

<?php 
    $message = "Another test!";
    echo $message;
?>

So what is it that I need to do to pass php variable $message into the paragraph using jquery ajax?

I know I could simply do if I changed index.html to index.php, but then if $message later changes, I have to reload the page. I am trying to learn how to make dynamic content without having to reload the page.

Thanks ahead of time for any help you provide! :-)

3个回答



您必须等到数据返回后再使用它:</ p>

   $(document).ready(function(){
$(“button”)。click(function(){
$ .get(“return.php”,function(data){
$( “p”)。text(data);
});
});
});
</ code> </ pre>
</ div>

展开原文

原文

You'll have to wait until the data is returned before you can use it:

$(document).ready(function(){
    $("button").click(function() {
        $.get("return.php", function(data) {
             $("p").text(data);
        });
    });
});

duanlei1957
duanlei1957 谢谢! 那就做到了! :-)
7 年多之前 回复



get </ code>添加回调。</ p>

  $  .get(“return.php”,function(data){
$(“p”)。text(data);
});
</ code> </ pre>
</ div>

展开原文

原文

Add a callback to get.

$.get("return.php", function(data) {
    $("p").text(data);
});



您可以在。获得功能。 </ p>

  $(document).ready(function(){
$(“button”)。click(function(){
$ .get(“return.php” “,function(data){
$(”p“)。text(data);
});
});
});
</ code> </ pre>

在这里你也可以传递数据类型以及你希望服务器响应的形式。
假设你想从服务器返回任何其他数据类型(即json),只需像这样使用数据类型:</ p>

  $(document).ready(function(){
$(“button”)。click(function(){
$ .get(“return.php”,function(data) {
$(“p”)。text(data);
},“json”);
});
});
</ code> </ pre>

有关详细信息,请参阅: http://api.jquery.com/jQuery.get/ </ p>
</ div>

展开原文

原文

You can use callback function in .get function.

$(document).ready(function(){
    $("button").click(function() {
       $.get("return.php",function(data){
           $("p").text(data);
       });
    });
});

Here you can pass the datatype as well in which form you want the response from server. Suppose you want to return anyother datatype(i.e. json)from server, just use datatype with it like this :

 $(document).ready(function(){
        $("button").click(function() {
           $.get("return.php",function(data){
               $("p").text(data);
           },"json");
        });
    });

For more detail,refer : http://api.jquery.com/jQuery.get/

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐