JSON 响应 ajax 对 JS 变量的请求

JSON response at ajax request to JS variables

我正在尝试上传具有动态名称的文件并取回这些动态名称。

详细来说,我有 2 页 form.phpupload.php。当在 form.php 上按下上传按钮时,请求发送到 upload.php,其中 2 个文件(DLpath 和 PhotoIDPath)被上传到具有动态名称的服务器,例如:

DLpath=documents/20161130232311i8hGn0HzJT276415832.png

PhotoIDPath=documents/20161130232311SSRqCyIbKKalock.png.

它工作正常。然后在 upload.php 上,我将这些文件名编码为 JSON 数组 ,即

$response  = array ('DLpath'=>$Dlpath ,'PhotoIDPath'=>$PhotoIDPath);
echo json_encode($response);

而firebug快照是:

我想在 var jsDlpath 中获取 DLpath,在 var jsPhotoIDPath 中获取 PhotoIDPath

我用来获取响应的代码(无效)是:

complete: function(response) 
    {
    var jsDlpath=response.DLpath;
    var jsPhotoIDPath=response.PhotoIDPath;
alert(jsDlpath+" - "+jsPhotoIDPath)
}

和警报显示:

undefined - undefine

如果你能帮我把js变量中的那些值gwt,我会非常感谢你。

因为你在服务器端编码你 response 你应该在 js 端解析它,你可以使用 $.parsejson() :

success: function(response) 
{
    var response = $.parseJson(response);
     //if $.parseJson dont work, use JSON.parse

    var jsDlpath=response.DLpath;
    var jsPhotoIDPath=response.PhotoIDPath;

    alert(jsDlpath+" - "+jsPhotoIDPath)
}

注意: 使用 success/done 回调而不是完成。

希望对您有所帮助。

如果运行纯javascript你会发现有两个响应属性:responseText和responseXML。你可能想要:

var data = JSON.parse(response.responseText);

一个完整的示例,使用 https://gist.github.com/bitdivine/7ddd943387a4350336dd 中的 curl(但 jquery 也可以)在 Github:

上找到未解决的问题
curl('https://api.github.com/repos/gchq/CyberChef/issues?state=open')
.then((res) => JSON.parse(res.responseText))
.then((data) => console.log(data))