0

我有以下 PHP 代码,它从发布的表单字段创建了 JSON 请求。

<?php
if ( isset($_POST['data']['Affiliate'])) { //Where ['data']['Affiliate'] is an array of posted field names of the form.
    $data = $_POST['data'];

    $base = 'https://api.whatever.com/Api?';

    $params = array(
        'Format' => 'json'
        ,'account' => $data['Affiliate']
    );

    $url = $base . http_build_query( $params );
    $result = file_get_contents( $url );
    $result = json_decode( $result );

    echo "<pre>";
    print_r( $result );
    echo "</pre>";
?>

print_r( $result )打印以下内容。

stdClass Object
(
    [request] => stdClass Object
        (
            [Format] => json
            [account] => stdClass Object
                (
                    [country] => US
                    [address1] => asdasd
                    [city] => asdasd
                    [zipcode] => asdasd
                    [phone] => asdasd
                )
        )

    [response] => stdClass Object
        (
            [status] => -1
            [data] => 
            [errors] => Array
                (
                    [0] => stdClass Object
                        (
                            [err_code] => 3
                            [err_msg] => A user already exists with this email address.
                            [attribute_name] => Email
                            [publicMessage] => User account or user is not valid.
                        )
                    [1] => stdClass Object
                        (
                            [err_code] => 1
                            [err_msg] => City cannot be blank.
                            [attribute_name] => city
                        )
                )
        )
)

我如何使用 JQuery Ajax 来实现相同的结果并打印出<li>标签中的错误数组。

4

2 回答 2

3
var errorsArr='';
var affiliate='';
//affiliate is your data of $data['Affiliate'] which you can get using jquery or js..
$.ajax({
    url:'https://api.whatever.com/Api?'
    data:{Format: 'json',account : affiliate},
    dataType:'json',
    success:function(data){
      errorsArr=data.response.errors;
    }
  }
});

您将在errorsArr 中得到所有错误。它是一个 json 数组,您可以对其进行迭代以获得所需的输出

于 2012-09-22T06:54:24.687 回答
0

我建议您不要像在此处那样将 JSON 解码为 PHP 对象,而是保留纯 JSON,将其提供给您的 AJAX 请求,然后在客户端进行解码(我相信有一个特殊的 jquery ajax 函数可以获得并已经为您解码。请参阅 Ravi 的答案)

但是,如果您不想这样做:为什么不访问您从中获得的对象的字段json_decode()
我相信这$result->$response->$errors是您正在寻找的一系列错误。

于 2012-09-22T06:55:56.917 回答