Domanda

I'me trying to use ajax with php, I have the follogin script in php :

<?php

// this file get the POST infor sent by a AJAX request and will return the value is succesful.

$price['name'] = "Called";
$price['Wheel']  = 75.25;
$price['Tire']   = 50.00;

echo json_encode($price);
?>

and I'm calling this code from my main page in the following way :

        $.post("ajax/profileMod.php", {
            'lname':lname,
            'fname':fname,
            'mname':mname,
            'language':language,
            'title':title,
            'ptype':ptype,
            'vip':vip,
            'vreason':vreason
        })
        // Retreive the data from the php script
        .done(function(data) {
         // php code : echo json_encode(array("name"=>"Called!"));
            alert(data);
        }, "json");

        // Stop original behavior
        return false;
    });

The returniong result from the alert is the following test : {"name":"Called",Wheel":75.25,"Tire":50}

How can I change this result so I may use it in the following way in javascript EX:

alert(myresult['Name']) ; Would give me "Called".

So I basicly would like a associative array in javascript, but I read somewhere on this forum that you can't have associative array in Javascript, only object...

Please help!

È stato utile?

Soluzione

Pass "json" as the last parameter to .post() to tell jQuery to parse the response as JSON.
(or, fix your server to return the correct Content-Type of application/json, and jQuery should do that automatically)

You will then get a Javascript object, allowing you to write

alert(result.name);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top