简体   繁体   中英

Can I use a variable to pass a json string?

This code works:

$(this).load($('.pageloadlabel', this).attr('href'), {category: 1});

This code doesn't work:

var data = '{category: 1}';
$(this).load($('.pageloadlabel', this).attr('href'), data);

The question is, how can I make it work?

It's not JSON, it's a javascript object.

var data = { category: 1 };

If you have a string, you would have to convert it to a object .

And notice that your string is not a valid JSON, see the link for more details.

删除引号,加载函数需要一个对象,而不是字符串。

Your data is not a Javascript object but a string, you can convert it to object by eval eg

data = eval('(' + data + ')');

but eval is considered dangerous, so better to parse string as JSON eg

data = JSON.parse(data)

For JSON lib you can use json2

Have you tried to use eval() on data?

var data = '{category: 1}';
$(this).load($('.pageloadlabel', this).attr('href'), eval(data));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM