如何将数据从PHP返回到jQuery ajax调用

时间:2022-10-08 08:43:20

I am posting some data using ajax. I want to manipulate that data and return to to the calling jQuery script.

我正在使用ajax发布一些数据。我想要操作该数据并返回到调用jQuery脚本。

Here is my jQuery:

这是我的jQuery:

$.ajax({
  type: "POST",
  url: "somescript.php",
  datatype: "html",
  data: dataString,
  success: function() {
    //do something;
    }
});

Here is my somescript.php on the server:

这是我的somescript。php服务器上:

  <?php
    //manipulate data
    $output = some_function(); //function outputs a comma-separated string
    return $output;
  ?>

Am I doing this correctly on the server side, and how do I access the return string when the ajax call completes?

我是否在服务器端正确地执行了此操作,以及在ajax调用完成后如何访问返回字符串?

3 个解决方案

#1


64  

I figured it out. Need to use echo in PHP instead of return.

我想出来。需要在PHP中使用echo而不是return。

<?php 
  $output = some_function();
  echo $output;
?> 

And the jQ:

金桥:

success: function(data) {
  doSomething(data);
}

#2


11  

It's an argument passed to your success function:

这是传递给你的成功函数的一个参数:

$.ajax({
  type: "POST",
  url: "somescript.php",
  datatype: "html",
  data: dataString,
  success: function(data) {
    alert(data);
    }
});

The full signature is success(data, textStatus, XMLHttpRequest), but you can use just he first argument if it's a simple string coming back. As always, see the docs for a full explanation :)

完整的签名是成功的(data, textStatus, XMLHttpRequest),但是如果返回的是一个简单的字符串,您可以使用he first参数。一如既往,请参阅文件以获得完整的解释:)

#3


2  

Yes, the way you are doing it is perfectly legitimate. To access that data on the client side, edit your success function to accept a parameter: data.

是的,你这样做是完全合法的。要访问客户端上的数据,请编辑success函数以接受参数:data。

$.ajax({
    type: "POST",
    url: "somescript.php",
    datatype: "html",
    data: dataString,
    success: function(data) {
        doSomething(data);
    }
});

#1


64  

I figured it out. Need to use echo in PHP instead of return.

我想出来。需要在PHP中使用echo而不是return。

<?php 
  $output = some_function();
  echo $output;
?> 

And the jQ:

金桥:

success: function(data) {
  doSomething(data);
}

#2


11  

It's an argument passed to your success function:

这是传递给你的成功函数的一个参数:

$.ajax({
  type: "POST",
  url: "somescript.php",
  datatype: "html",
  data: dataString,
  success: function(data) {
    alert(data);
    }
});

The full signature is success(data, textStatus, XMLHttpRequest), but you can use just he first argument if it's a simple string coming back. As always, see the docs for a full explanation :)

完整的签名是成功的(data, textStatus, XMLHttpRequest),但是如果返回的是一个简单的字符串,您可以使用he first参数。一如既往,请参阅文件以获得完整的解释:)

#3


2  

Yes, the way you are doing it is perfectly legitimate. To access that data on the client side, edit your success function to accept a parameter: data.

是的,你这样做是完全合法的。要访问客户端上的数据,请编辑success函数以接受参数:data。

$.ajax({
    type: "POST",
    url: "somescript.php",
    datatype: "html",
    data: dataString,
    success: function(data) {
        doSomething(data);
    }
});