如何将json字符串发送回jquery [英] How to send a json string back to jquery

查看:100
本文介绍了如何将json字符串发送回jquery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将一些数据发送到外部php页面,并且该页面必须将所需的数据发送回jQuery.我的问题是如何将数据从外部页面发送回发送页面的jQuery.

I need to send some data to an external php page and that page has to send the required data back to jQuery. My question is how can I send the data from the external page back to jQuery on the page that send it.

这是将数据发送到外部页面的jQuery代码:

This is the jQuery code that sends the data to the external page:

function LoadImageData(url)
{    
    $.ajax({
      url: 'get_image_data.php',
      dataType: 'json',
      data: {'url': url },
      success: SetTag()
    }); 
}

这是htat接收数据的PHP代码,需要将其发送回一些数据:

This is the PHP code htat receives the data and is required to send some data back:

<?php
require_once('FaceRestClient.php');

$apiKey = '**********************';
$apiSecret = '**********************';
$api = new FaceRestClient($apiKey, $apiSecret);

$active_url = $_POST['url'];
$photos = $api->faces_detect($active_url);

return $photos;
?>

所以我的问题是,如何将数据发送回jQuery.只是简单的退货似乎行不通.

So my problem is, how can I send the data backto jQuery. Just a simple return does not seem to work.

在此先感谢您, 标记

推荐答案

有人会认为REST API会为您提供JSON,但是您需要检查它是否有效JSON(此处的JSONP无效)?

One would think the REST API would give you JSON, but you need to check if it's valid JSON (JSONP is not valid here) ?

您只需将dataType放在Ajax函数中,然后让jQuery弄清楚,这样,如果它不是有效的JSON,您至少会得到一些回报.

You could just drop the dataType in your Ajax function and let jQuery figure it out, that way atleast you'll get something back if it's not valid JSON.

尝试一下:

$.ajax({
      url: 'get_image_data.php',
      type: 'POST',
      data: {'url': url }
    }).done(function(data) {
       console.log(data);
    }).fail(function() {
       console.log('Your ajax just failed');
});

打开控制台,查看打印的内容

Open the console, and see what is printed

在PHP函数的结尾,我倾向于这样做:

At the end of a PHP function I tend to do :

exit(json_encode($someData));

以JSON形式返回数据,但可以打印数据的任何事情.

To return the data as JSON, but anything that prints the data is ok.

这篇关于如何将json字符串发送回jquery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆