2015-10-16 80 views
0

我正在嘗試從MySql和PHP的HTML中顯示圖像。成功顯示圖像ajax

我的Ajax請求

$.ajax({ 
    type : "POST",  
    url : "jsonajax.php", 
    data : { id: id }, 
    success : function(data){ 
     alert(data); 
     $('#dialog').dialog('open'); 
     $('#dialog').html('<img src='+ data + '" />'); 
    } 
}); 

我jsonajax.php

$id = $_REQUEST['id']; 
$sql = "SELECT img_url FROM table_name WHERE id = $id"; 
$res=$obj->_executeQuery($sql); 
$res=$obj->getAll($res); 
echo json_encode($res); 

現在alert(data)看起來像

[{"img_url":"images\/Jellyfish.jpg"}] 

我需要刪除 '\' 和圖像SRC追加到顯示。

回答

0

嘗試

JSON.parse(data) 

這將數據

0

解碼添加dataType:"json"

$.ajax({ 
    type : "POST", 
    dataType: "json",  
    url : "jsonajax.php", 
    data : { id: id }, 
    success : function(data){ 
     alert(data); 
     $('#dialog').dialog('open'); 
     $('#dialog').html('<img src='+ data + '" />'); 
    } 
}); 

然後做data.img_url

+0

這是行不通的。我的回覆看起來像這個'[{「img_url」:「images \ /Jellyfish.jpg」}]'。我需要把價值放在img src上。 – Loura

+0

將其添加到src屬性中時刪除反斜槓。 IMAGEURL = data.img_url; data = Imageurl.replace(/ \\「/ g,'''); – suresh

1

您需要添加一個數據類型,像 「類JSON」

0

你需要轉換的字符串響應對象 - 這將自動地刪除斜線:)

選擇1:JSON.parse(data)

選2分析數據:您可以在$.ajax指定dataType: 'json'選項請求。

$.ajax({ 
    type : "POST",  
    url : "jsonajax.php", 
    data : { id: id }, 
    dataType: 'json', // This is what you're missing 
    success : function(data){ 
     $('#dialog').html('<img src='+ data.image_url + '" />'); 
     $('#dialog').dialog('open'); 
    } 
}); 

結帳的文檔具體的數據類型選項:http://api.jquery.com/jquery.ajax/

0

作出這樣的AJAX塊(在您的情況):

$.ajax({ 
    type : "POST",  
    url : "jsonajax.php", 
    data : { id: id }, 
    dataType: 'json', 
    success : function(data){ 
     console.log(data); 
     $('#dialog').dialog('open'); 
     $('#dialog').html('<img src=' + data[0].img_url + '" />'); 
    } 
}); 

希望這有助於。

注意:請確保圖像位於當前腳本的images文件夾中。