user3135626
user3135626

Reputation: 87

Converting string to an object

Below is the code I am working on, my goal is to convert string to an actual object and just simply display the data from ajax call. But it seems that the string value cant work this way.

var string = "first: 'George', last: 'Smith'";

$.ajax({
   type: 'POST',
   url: 'ajax.php',
   data: {string}
}).done(data){
   alert(data);
}

Upvotes: 0

Views: 60

Answers (3)

user1636522
user1636522

Reputation:

Try this :

data: Function('return {' + string + '};')()

Upvotes: 1

givanse
givanse

Reputation: 14943

What you are looking for is:

  1. Do an AJAX call and receive data.
  2. The received data will be a string, but with a special format, what many use is Json.
  3. You'll create your object "manually".
  4. Then, you'll populate your object's fields with the Json values.

There are plenty of examples on the web.

Upvotes: 0

Sai Avinash
Sai Avinash

Reputation: 4753

Can you try this:

var Params= {first: 'George', last: 'Smith'};

$.ajax({
    type: "Post",
                dataType: 'json',
                url: 'ajax.php',
                data: JSON.stringify(Params),
                contentType: 'application/json',}).done(data){
   alert(data);
}

Upvotes: 0

Related Questions