Reputation: 2898
I have the following script which works as expected , it retrieves an XML list and assigns some variables
$.ajax({
type: "POST",
url: "pgGeneral_login/validate.php",
data: { user:user , pass:pass },
dataType: "xml",
success:loginval });
function loginval(data){
console.log("Returned" )
valid = $(data).find('valid').text();
name = $(data).find('name').text();
pass = $(data).find('pass').text();
};
What I would like to do is instead of assigning a variable to each of the xml results (valid = $(data).find('valid').text() ) is loop through the list an assign the value to the tag name without writing a huge list of code , if it was php I would use something like
foreach ($row as $k => $v)
$$k = $v
any help please ?
Upvotes: 2
Views: 182
Reputation: 11588
As an addendum to ATOzTOA's code, this will also allow you to dynamically add variables to the global scope (i.e. for use outside of your AJAX functionality). It uses the eval()
function which is generally avoided in most JS development:
// Array of fields you want to traverse
var array = ['text', 'name', 'pass'];
// This is the data object you get from your AJAX function
var vals = {
text: 'Hello',
name: 'John',
pass: 'Password'
};
// Loop through and assign your vars
for (var i = 0; i < array.length; ++i) {
var key = array[i];
eval('var ' + key + ' = "' + vals[key] + '"');
}
console.log(text);
Thought it was an interesting question, so this answer is purely to offer an alternative (if hypothetical) solution - I'd err on the side of caution if using this for production purposes.
Upvotes: 2
Reputation: 35950
This will directly update global variable list and is not recommended.
Here you go,
function loginval(data){
console.log("Returned" )
// valid = $(data).find('valid').text();
// name = $(data).find('name').text();
// pass = $(data).find('pass').text();
$(data).children().each(function(){
// Directly adding to the Global list
window[this.tagName] = $(this).text();
});
console.log(valid);
console.log(name);
}
Upvotes: 3
Reputation: 1754
Thought its not quite what you could achieve with php, but I think it somewhat does what you want:
function loginval(data){
console.log("Returned" )
$dataList={};
$(data).children().each(function(){
$dataList[this.tagName]=$(this).text();
});
console.log($dataList )
}
Upvotes: 1