开发者

Invalid JSON Primitive when using a variable

I have code that makes an AJAX call to an MVC controller method and it'll work without a hitch if I do this:

var obj = '{"titlename":"whatever"}';
            $.ajax({
                type: "POST",
                url: "/Titles/Yo",
                contentType: "application/json; charset=utf-8",
                dataType: 'json',
                data: obj,
                success: function (result) {
                    $("#title_field").html(result.TitleName开发者_Go百科);
                }
            });

But if I do this:

var stringed="whatever"
            var obj = '{"titlename":stringed}';
            $.ajax({
                type: "POST",
                url: "/Titles/Yo",
                contentType: "application/json; charset=utf-8",
                dataType: 'json',
                data: obj,
                success: function (result) {
                    $("#title_field").html(result.TitleName);
                }
            });

It craps out on me with an "invalid JSON primitive" error. I keep trying various single and double quote permutations, but they all keep giving me the same error. How can I insert a string variable into a JSON object?


Try this:

var stringed = "whatever";
var obj = '{"titlename": "' + stringed + '"}';

Also you may want to take a look at a JSON2 library, which can stringify your data automatically.


Why are you declaring your object as a String?

Have you tried doing:

var stringed="whatever";
var obj = {
   "titlename":stringed
 };


var obj = {"titlename":stringed};

This is probably what you need.


Try this:

  var stringed="whatever";
   var obj = {"titlename": stringed};
    $.ajax({
        type: "POST",
        url: "/Titles/Yo",
        contentType: "application/json; charset=utf-8",
        dataType: 'json',
        data: obj,
        success: function (result) {
            $("#title_field").html(result.TitleName);
        }
    });

What you had was just a string that contained the the string "stringed", you need a object literal.

jQuery can take an object and it'll take care of sending the json string to the server instead.


You should do:

var stringed="whatever";
var obj_as_object = {titlename: stringed};
var obj_as_string = JSON.stringify(obj_as_object);

...
data: obj_as_string  //This goes in your ajax call

With this, we're auto encoding the obj with JSON.

JSON.stringify will work in modern browsers. If you want support to an older browser (for example, IE6) you should use a library such as json2 from http://json.org.

Hope this helps. Cheers


This isn't a great way to do it but..

var stringed="whatever"
var obj = '{"titlename":'+stringed+'}';

Or

var obj = {
  "titlename":stringed
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜