【问题标题】:Send PHP's JSON response from an API call as part of AJAX success function作为 AJAX 成功函数的一部分,从 API 调用发送 PHP 的 JSON 响应
【发布时间】:2019-04-04 07:14:53
【问题描述】:

我已经设置了一个页面,该页面从表单中获取数据,序列化为 JSON,然后使用 AJAX 调用 PHP 文件来处理表单数据并通过 cURL 将其发送到 API。

如何从 API 获取响应以作为 AJAX 成功函数的一部分返回?

在我的项目开始时,我能够做到这一点,因为我使用 php 作为包含。但不能使用该方法,因为文件是从 AJAX 调用而不是从包含执行的。

我尝试关注this tutorial,但不断发现错误。

我还从这个网站上的各种帖子中搜索、审查和尝试了更多的建议,我什至无法计算。现在,我正在寻求帮助。

这是我的 index.php 文件中的相关 ajax。

$.ajax
({
    type: "POST",
    dataType : 'json',
    async: false,
    url: 'save_application.php',
    data: { filename: fileName,  applicationData: jsonFormString, job: adid },
    success: function () { console.log("done");},
    failure: function() {console.log('error');}
});

这里是 save_application.php 文件的相关部分。

$curl = curl_init();

curl_setopt_array($curl, array(
  //stuff here
));

$applicantresponse = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

最后,返回的 $applicantresponse 格式如下:

{
  "applicationId": 123456789,
  "links": {
    "link1": "https://thisisalinkforLINK1.html", //THIS IS THE VALUE I WANT
    "link2": "https://thisisalink.html",
    "link3": "https://thisisalink.html"
  }
}

最终,我想将变量设置为 links->resume 的值(例如:var resumeLink = (something goes here); \\returns https://thisisalinkforLINK1.html) 回到我的成功函数中的 index.php 上,这样我就可以将该响应用于其他一些待办事项。

【问题讨论】:

  • 您需要输出对 jQuery 代码的响应,这在此处不会发生。你的 PHP 有输出吗?

标签: php ajax api


【解决方案1】:

您需要从您的save_application.php 文件中输出$applicantresponse,以便将其返回给您的调用代码,并且您需要更改您的ajax 代码中的success 函数以使用该数据。它看起来像这样:

$applicantresponse = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

echo json_encode($applicantresponse);

然后……

$.ajax
({
    ...
    success: function (data) {
        console.log(data.links.link1);
        // do something with the data that was returned
    },
    ...
});

重要的一点是您的 php 代码不会向客户端输出 任何 其他文本。所有其他echoprint、调试调用,所有这些东西,都必须删除,否则你不会发回 jQuery 知道如何解释的有效 json 编码数据。

【讨论】:

    【解决方案2】:

    貌似save_application.php使用了$.ajax提交的数据进行curl请求,需要将部分curl响应发回客户端用于成功函数。

    curl 响应已经是 JSON,所以最简单的方法就是

    echo $applicantresponse;
    

    这会将整个 curl 响应发送回客户端。

    如果您只想发送其中一个链接,则需要对其进行解码并提取您想要的特定片段,然后重新编码该片段。

    $applicantresponse = json_decode($applicantresponse);
    $link = $applicantresponse->links->link1;
    echo json_encode($link);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-11
      • 2015-11-12
      • 1970-01-01
      • 2017-01-21
      • 2018-01-08
      • 2018-05-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多