2016-11-30 62 views
1

我想用動態名稱上傳文件並獲取這些動態名稱。對JS變量的ajax請求的JSON響應

詳細說來,我有2頁form.phpupload.php。當按下上form.php然後請求發送到upload.php,其中2個文件(DLpath和PhotoIDPath)被上傳到服務器以動態名稱上傳按鈕,例如:

DLpath =文檔/ 20161130232311i8hGn0HzJT276415832.png

而且

PhotoIDPath = documents/20161130232311SSRqCyIbKKalock.png

它工作正常。然後在upload.php,我編碼的文件名作爲JSON陣列

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

而且螢火蟲快照:

enter image description here

我想DLpath在var jsDlpath和PhotoIDPath在var jsPhotoIDPath

而我的代碼(不工作)得到的迴應是:

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

和報警顯示:

undefined - undefine

如果你能幫助我在GWT JS變量這些價值觀,我會很感激你的。

+0

你解析了'response'? ..嘗試登錄'response',如果它是一個字符串..使用'JSON.parse'解析它到'json對象' – noobHere

+1

你在'response'中接收了什麼?你可以在這裏發佈嗎? – 31piy

+1

我認爲你應該在成功沒有完成 – rad11

回答

1

既然你編碼你在服務器端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回調,而不是完整的。

希望這會有所幫助。

0

如果以純javascript運行,您會發現有兩個響應屬性:responseText和responseXML。你可能想:

一個完整的例子,使用curl從https://gist.github.com/bitdivine/7ddd943387a4350336dd(但jQuery將做精爲好)來獲得開放性問題在Github上:

curl('https://api.github.com/repos/gchq/CyberChef/issues?state=open') 
.then((res) => JSON.parse(res.responseText)) 
.then((data) => console.log(data))