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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2410773/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:27:38  来源:igfitidea点击:

How to return data from PHP to a jQuery ajax call

jqueryajax

提问by user191688

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 调用完成时访问返回字符串?

回答by user191688

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:

和 jQ:

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

回答by Nick Craver

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:)

完整的签名是success(data, textStatus, XMLHttpRequest),但如果它是一个简单的返回字符串,您可以只使用他的第一个参数。与往常一样,请参阅文档以获得完整的解释:)

回答by Aaron

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.

是的,你这样做是完全合法的。要在客户端访问该数据,请编辑您的成功函数以接受一个参数:data。

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

回答by DEEPAK

based on accepted answer

基于接受的答案

$output = some_function();
  echo $output;

if it results array then use json_encode it will result json array which is supportable by javascript

如果结果数组然后使用 json_encode 它将导致 javascript 支持的 json 数组

$output = some_function();
  echo json_encode($output);

If someone wants to stop execution after you echo some result use exit method of php. It will work like return keyword

如果有人想在您回显某些结果后停止执行,请使用 php 的退出方法。它会像 return 关键字一样工作

$output = some_function();
  echo $output;
exit;