0

私は次の関数を持っているphpスクリプトを持っています:

<?php
function readXML() {
    $url = $_REQUEST['schemaPath'];

    $xml = simplexml_load_file($url);

    $fields = $xml -> fields -> field;
    GLOBAL $array;
    GLOBAL $c;
    $array = new stdClass;
    foreach($fields as $field->attributes){
        foreach($field->attributes->attributes() as $a => $b){
            if($a == "name") {
                $c = $b;
            }
            if($a == "type") {
                $array -> $c = $b;
            }
        }
    }
    return json_encode($array);
}
echo readXML();
?> 

私は次の方法でajax呼び出しを行っています:

$.ajax({
                cache: false,
                url: "readXML.php",
                type: "POST",
                dataType: 'jsonp',
                jsonp: 'jsonp_callback',
                data: { schemaPath: "http://localhost:8983/solr/admin/file/?file=schema.xml" },
                crossDomain: true,
                success:function(data) {
                    if (!data) {
                        alert("Error in processing xml file");
                        return null;
                    } else {                
                        console.log(data);
                    }
                },
                error:function(data) {
                    alert("Error while reading schema file.");
                    $("#loadingStatus").hide();
                }
            });

目的のjson応答形式が得られません。Error while reading schema file応答でアラートを受け取ります。私は実際にそれをのkey:valueようなパターンにしたいと思っています$c:$bが、それはのように来てい$c:{"0":$b}ます。有効なjson応答を取得できるように、phpスクリプトから配列を返す方法。

4

2 に答える 2

0

I got the solution why on completion of ajax call it was always going to the error function. Here i am doing jsonp in the ajax call but was not handling the same in the php script. To solve this problem and to return a proper response need to add the following in the php script :

if(isset($_REQUEST['jsonp'])) {
        echo $_REQUEST['jsonp'].'('.json_encode($array).')';
    }else{  
        echo json_encode($array);
    }

And to make the response as key:value need to change the $array[$c] = $b; to $array[$c] = (string)$b; along with the change pointed by @EmmanuelG in his answer.

于 2012-12-05T18:53:31.750 に答える
0

stdClassを使用する代わりに、通常の連想配列を使用しないのはなぜですか。これにより、最小限の変更で問題が修正されます。

<?php
function readXML() {
    $url = $_REQUEST['schemaPath'];

    $xml = simplexml_load_file($url);

    $fields = $xml -> fields -> field;
    GLOBAL $array;
    GLOBAL $c;
    $array = array(); // changed
    foreach($fields as $field->attributes){
        foreach($field->attributes->attributes() as $a => $b){
            if($a == "name") {
                $c = $b;
            }
            if($a == "type") {
                // cast the $c to convert the value from a SimpleXMLObject 
                // to a string for use within the key
                $c = (string)$c; 
                $array[$c] = $b;
            }
        }
    }
    return json_encode($array);
}
echo readXML();
?> 
于 2012-11-30T15:26:46.317 に答える