简体   繁体   中英

json_encode to send data back to js

Im creating a simple upload script. I use a simple form to let people upload a picture and then a external php script will upload the picture and return some vars to the upload page.

But I cant get the part to return some vars to work. currently im using this:

The page that also contains the form:

form_data.append('file', file_data);
$.ajax({
            url: 'upload.php', // point to server-side PHP script 
            dataType: 'text',  // what to expect back from the PHP script, if anything
            cache: false,
            contentType: false,
            processData: false,
            data: form_data,                         
            type: 'post',
            success: function(response){
                document.getElementById("titel" + amount).innerHTML = response['naam'];

});

The upload page that should return some data:

echo json_encode(array('naam'=>$naam));

This scripts returns undefined..

If I remove the ['naam'] after response on the form page it will print out: {"naam":"test.png"}

Hope someone know what im doing wrong. Thanx in advance!

You said:

dataType: 'text',  // what to expect back from the PHP script, if anything

… so jQuery will ignore what the server claims the data is (which seems to be HTML as you haven't changed the Content-Type header in your PHP) and process the response as if it was plain text.

response will therefore be a plain text string and not the results of parsing JSON.

Change dataType to "json" .

The response you get from the server is the string . To use it as object, you need to parse it to JSON format using JSON.parse() .

var obj = JSON.parse(response);

Then you can use:

obj.naam;

to get the value of naam from the object.

Please change datatype from "text" to "json" then parse that JSON using JSON.parse(//return value ").

Var jsonObject = JSON.parse("Ajax Response object"); then use it jsonObject.keyName and it will return the value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM