简体   繁体   English

json_encode将数据发送回js

[英]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. 我使用一种简单的形式让人们上传图片,然后外部php脚本将上传图片并将一些变量返回到上传页面。

But I cant get the part to return some vars to work. 但是我无法让一部分的var恢复正常工作。 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"} 如果我在表单页面上回复后删除了['naam'],它将打印出:{“ 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. …因此jQuery将忽略服务器要求的数据(似乎是HTML,因为您没有更改PHP中的Content-Type标头),并像处理纯文本一样处理响应。

response will therefore be a plain text string and not the results of parsing JSON. 因此, response将是纯文本字符串,而不是解析JSON的结果。

Change dataType to "json" . dataType更改为"json"

The response you get from the server is the string . 您从服务器获得的响应是string To use it as object, you need to parse it to JSON format using JSON.parse() . 要将其用作对象,您需要使用JSON.parse()将其解析为JSON格式。

var obj = JSON.parse(response);

Then you can use: 然后,您可以使用:

obj.naam;

to get the value of naam from the object. 从对象中获取naam的值。

Please change datatype from "text" to "json" then parse that JSON using JSON.parse(//return value "). 请将数据类型从“文本”更改为“ json”,然后使用JSON.parse(//返回值“)解析该JSON。

Var jsonObject = JSON.parse("Ajax Response object"); Var jsonObject = JSON.parse(“ Ajax响应对象”); then use it jsonObject.keyName and it will return the value. 然后使用它jsonObject.keyName,它将返回值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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