Javascript Json object, get by value by Key String.. Ex : GetMyVal(MyKeyInString)
I have this json info:
data.ContactName
data.ContactEmal
data.Departement
I Would like to have a function like that
function GetMyVal(myStringKey)
{
$.Ajax
,...
, ...
,success :function(data)
{
$("#mytarget").val(data.myStringKey);
}
}
Call 开发者_运维技巧Like that GetMyVal("ContactName");
Solution:
Try changing:
$("#mytarget").val(data.myStringKey);
to:
$("#mytarget").val(data[myStringKey]);
Explanation:
Here is what those constructs mean:
$("#mytarget").val(SOMETHING);
change the value of the element with id "mytarget" to SOMETHING
data.myStringKey
take the object named "data" and give me the value of its property named literally "myStringKey"
data[myStringKey]
take the object named "data" and give me the value of its property named like a value of the variable named "myStringKey"
You can use something like this:
$('#mytarget').val(data[myStringKey]);
In JavaScript, the construct:
reference_to_object [ expression ]
means to evaluate the expression, and then use its string value as a property name to look up a property in the referenced object.
Just do this:
$("#mytarget").val(data[myStringKey]);
精彩评论