代码之家  ›  专栏  ›  技术社区  ›  Alekc

将js Array()转换为JSon对象以与JQuery.ajax一起使用

  •  27
  • Alekc  · 技术社区  · 16 年前

    var saveData = Array();
    saveData["a"] = 2;
    saveData["c"] = 1;
    alert(saveData);
    $.ajax({
        type: "POST",
        url: "salvaPreventivo.php",
        data:saveData,
        async:true
        });
    

    数组的索引是字符串而不是int,因此出于这个原因,saveData.join(“&”)之类的东西不起作用。

    思想?

    提前谢谢

    5 回复  |  直到 16 年前
        1
  •  65
  •   Paolo Bergantino    16 年前

    不要将其设置为数组如果它不是数组,请将其设置为对象:

    var saveData = {};
    saveData.a = 2;
    saveData.c = 1;
    
    // equivalent to...
    var saveData = {a: 2, c: 1}
    
    // equivalent to....
    var saveData = {};
    saveData['a'] = 2;
    saveData['c'] = 1;
    

    使用数组的方式只是利用Javascript对数组的处理,而不是真正正确的方式。

        2
  •  7
  •   Community Mohan Dere    5 年前

    Paolo Bergantino

        var saveData = Array();
        saveData["a"] = 2;
        saveData["c"] = 1;
        
        //creating a json object
        var jObject={};
        for(i in saveData)
        {
            jObject[i] = saveData[i];
        }
    
        //Stringify this object and send it to the server
        
        jObject= YAHOO.lang.JSON.stringify(jObject);
        $.ajax({
                type:'post',
               cache:false,
                 url:"salvaPreventivo.php",
                data:{jObject:  jObject}
        });
        
        // reading the data at the server
        <?php
        $data = json_decode($_POST['jObject'], true);
        print_r($data);
        ?>
    
        //for jObject= YAHOO.lang.JSON.stringify(jObject); to work,
        //include the follwing files
    
        //<!-- Dependencies -->
        //<script src="http://yui.yahooapis.com/2.9.0/build/yahoo/yahoo-min.js"></script>
    
        //<!-- Source file -->
        //<script src="http://yui.yahooapis.com/2.9.0/build/json/json-min.js"></script>
    

        3
  •  4
  •   dstnbrkr    16 年前

    您可以迭代saveData对象的键/值对以构建一个对数组,然后在生成的数组上使用join(&):

    var a = [];
    for (key in saveData) {
        a.push(key+"="+saveData[key]);
    }
    var serialized = a.join("&") // a=2&c=1
    
        4
  •  1
  •   Tarun Gupta    12 年前

    数组对象和JSON对象之间实际上有区别。您可以这样做,而不是创建数组对象并将其转换为json对象(使用json.stringify(arr)):

    var sels = //Here is your array of SELECTs
    var json = { };
    
    for(var i = 0, l = sels.length; i < l; i++) {
      json[sels[i].id] = sels[i].value;
    }
    

    不需要将其转换为JSON,因为它已经是JSON对象了。 json.toSource();

        5
  •  0
  •   Starx    13 年前

    如果字符串={“hello”} 以字符串形式出现={\'hello\'} 为了解决这个问题,后面可以使用以下函数来使用json解码。

    <?php
    function stripslashes_deep($value)
    {
        $value = is_array($value) ?
                    array_map('stripslashes_deep', $value) :
                    stripslashes($value);
    
        return $value;
    }
    
    $array = $_POST['jObject'];
    $array = stripslashes_deep($array);
    
    $data = json_decode($array, true);
    print_r($data);
    ?>