문제

When trying to use a JSON.stringify() method to turn an array of strings into a JSON object that I can pass through to a PHP script, the stringify() method fails to return anything of significance.

This is the only code that the input is being passed through. It is not being tampered with by anything else.

function submitItem() {
 try {
    var item = [];
    item.name = $('.itemText').val();
    item.type = $('.itemType').val();
    item.price = $('.itemPrice').val();
    item.color = $('.itemColor').val();
    item.desc = $('.itemDesc').val();
    item.image = $('.itemImage').val();
    item.giftType = $('.itemGiftType').val();
    item.avail = $('.itemAvail').val();
    item.giftable = $('.itemGiftable').val();
    item.ranking = $('.itemRanking').val();
    item.basicTrack = $('.itemBasic').val();
    item.vetTrack = $('.itemVet').val();
    item.month = $('.itemMonth').is(':checked');
    item.hidden = $('.itemHidden').is(':checked');
    item.id = $('.itemID').val();

     //Left in for confirmation purposes
    var join = [];
    join[0] = 'test';
    join[1] = 'tset';
    console.log( JSON.stringify( join ) );

    console.log(item);
    var JsonItem = JSON.stringify(item);
    console.log( JsonItem );
 } catch (err) {
    console.log(err.message);
 }
}

This produces the following output in the console:

The output corresponds to the three console.log() lines at the bottom of the script

As you can see, the log for both JSON items returns as [] rather than any JSON string of any sort.

Any potential reason that this would occur would be appreciated.

Thanks.

도움이 되었습니까?

해결책

You're initializing your "item" as an array. You should be initializing it as a plain object ({}):

var item = {};

When the JSON serializer sees an actual array, it only operates on the numerically-indexed properties.

다른 팁

You should convert join to object before stringify

console.log( JSON.stringify( {arr: join}) );
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top