最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript string to variable - Stack Overflow

programmeradmin4浏览0评论

I am receiving a JSON string from an ajax call and would like to convert a value to a predefined variable:

var predefined = "hello world";
var foo = {"msg":"predefined"}; // JSON string

I want to echo out the standard string accessing it with

alert(foo.msg)

EDIT: to make the answer more clear here is my call:

var success_msg = "Your email is send successfully!";

$.ajax({
    url: "ajax-share-email.php",
    type: "POST", 
    dataType: "json", 
    data: {},
    success: function(data) {
        if (data.status == "success") {
            msg.text(data.msg).addClass("email-msg-success");                   
        } else {
            msg.text(data.msg).addClass("email-msg-error");
        }
    }
})

ajax-share-email.php responds:

{"status":"success", "msg":"success_msg"}

I am receiving a JSON string from an ajax call and would like to convert a value to a predefined variable:

var predefined = "hello world";
var foo = {"msg":"predefined"}; // JSON string

I want to echo out the standard string accessing it with

alert(foo.msg)

EDIT: to make the answer more clear here is my call:

var success_msg = "Your email is send successfully!";

$.ajax({
    url: "ajax-share-email.php",
    type: "POST", 
    dataType: "json", 
    data: {},
    success: function(data) {
        if (data.status == "success") {
            msg.text(data.msg).addClass("email-msg-success");                   
        } else {
            msg.text(data.msg).addClass("email-msg-error");
        }
    }
})

ajax-share-email.php responds:

{"status":"success", "msg":"success_msg"}
Share Improve this question edited Jan 9, 2011 at 15:19 TunaFFish asked Jan 9, 2011 at 14:57 TunaFFishTunaFFish 11.3k34 gold badges98 silver badges137 bronze badges 7
  • 5 Why not keep the predefined messages on the server side and just send the actual message? – tvanfosson Commented Jan 9, 2011 at 15:00
  • 1 @tvanfosson To keep the JSON small perhaps. – Hemlock Commented Jan 9, 2011 at 15:08
  • I am reconsidering this now, cheers! – TunaFFish Commented Jan 9, 2011 at 15:10
  • @tvanfosson Another good reason would be to consider this from an MVC perspective. The server could be an external API sending model-level information and the client is acting as the view, transforming geeky response codes into pretty HTML and human-readable messages. – Phrogz Commented Jan 9, 2011 at 15:10
  • @Hemlock - yeah, maybe there are cases where this would be a real performance win (e.g., lots of large messages and high frequency AJAX calls), but doing it server side leads to a simpler client and faster initial download. I'd need to be convinced that it's really necessary. If you're only saving a few dozen or even hundred bytes per message, is is really necessary? – tvanfosson Commented Jan 9, 2011 at 15:14
 |  Show 2 more ments

5 Answers 5

Reset to default 5
var strings = {"predefined":"hello world"};
alert(strings[foo.msg]);

or e.g.

var messages = {};
messages.success_msg = "Your email is send successfully!";

// ...
            msg.text(messages[data.msg]).addClass("email-msg-success");             

How about this -- just use the message inline on success and don't even bother to make it part of the JSON. On an error, do include the entire message and use it directly. Also, I'd have your server return something like:

{ "status": true }

or

{ "status": false, "msg": "The mail server is down." }

Then you can just evaluate it as a boolean without paring it to a string value.

$.ajax({
    url: "ajax-share-email.php",
    type: "POST", 
    dataType: "json", 
    data: {},
    success: function(data) {
        if (data.status) {
            msg.text('Your email has been sent successfully!').addClass("email-msg-success");                   
        } else {
            msg.text(data.msg).addClass("email-msg-error");
        }
    }
});

If, and only if, you start reusing your messages for multiple functions, then refactor to a message dictionary and reference it from there. Note your messages object would likely need to be a global variable, or at least in the outer scope of all the functions that use it.

 var messages = {};
 messages.mail_success = 'Your email has been sent successfully!';
 messages.post_success = 'Your data has been updated!';

$.ajax({
    url: "ajax-share-email.php",
    type: "POST", 
    dataType: "json", 
    data: {},
    success: function(data) {
        if (data.status) {
            msg.text(messages.mail_success).addClass("email-msg-success");                   
        } else {
            msg.text(data.msg).addClass("email-msg-error");
        }
    }
});
var predefined = "hello world";
var foo = {"msg":predefined}; // JSON string
alert(foo.msg)

?

IFF I understand what you are asking, I think I have all of the pieces here.

You have a variable predefined and you want to be able to return that in your json and have the resulting parsed object contain the value in predefined

JSON.parse will not work for you (at least not in Chrome), but eval will.

var predefined = "Hi! I'm predefined";
// ...

var json = '{"foo": predefined}'; // notice no quotes
var response = eval("(" + json + ")");
alert(response.foo);
var out = eval(foo.msg); // out is now "hello world"

Note: do not use eval() if you are not sure what the content of foo.msg is.

or

var out = foo.msg=="predefined" ? predefined : foo.msg;
发布评论

评论列表(0)

  1. 暂无评论