我在這裏新和jQuery開發,我有一個問題,爲什麼我不能使用數據類型:'json'和$ .parseJSON處理查詢返回從PHP到AJAX(jQuery)。發送AJAX,PHP查詢和返回JSON和AJAX不明白與「dataType:'json'」
reader.js
$(function(){
//Modal form which encapsulates the loading of information occurs
var modal = $('.modal');
//Encapsulates the existing list or the list elements, each element has an "edit" button
var lista = $('.lista');
lista.on('click','.actionedit',function(){
var id = $(this).attr('href');
var li = lista.find('li[class*="j_'+id+'"]');
$.ajax({
url: 'php/controller.php',
data: 'acao=consulta&editid='+id,
type: 'POST',
//contentType: 'application/json; charset=utf-8;',
dataType: "json",
error: function (xhr, ajaxOptions, thrownError) {
alert('Erro: "'+ xhr.status + '"\nMensagem: " ' + thrownError +'"');
},
beforeSend: function(){
li.css("background","#0F6") },
success: function(carga){
//alert(carga);
alert(carga.nome);
//modal.fadeIn("slow");
//modal.find('form span[class="filebar"]').text(carga.file);
//modal.find('form input[name="titulo"]').val(carga.title);
//modal.find('form textarea').append(carga.description;
},
complete: function(){ loader.fadeOut("slow"); },
});
return false;
});
});
Controller.php這樣
<?php
require_once("conexao.php");
switch($_POST['acao']){
case 'consulta':
//Validates query, that returns a json string...
$editid = $_POST['editid'];
$qr = "SELECT * FROM mod6_uploads WHERE id = '$editid'";
$ex = mysql_query($qr);
$st = mysql_fetch_array($ex);
//Return array in json format string for testing...
$u['file'] = 'File';
$u['title'] = 'File title';
$u['description'] = 'File Description';
echo json_encode($u);
break;
default:
echo 'Error querying';
}
因此,警報返回我以下消息:
Error: "200"
Message: "SyntaxError: JSON.parse: unexpected character"
如果我評論具體的數據類型:「json」,它返回我以下警告:未定義
如果我改變警報「警報(carga.nome)」到「警報(負載)」,它返回我下面的:
{"name": "File", "title": "File Title", "description": "File Description"}
而且,正如我剛纔所說,如果我使用$.ParseJSON
或JSON.parse
沒有任何回報,或者錯誤或成功。
有沒有人遇到類似這樣的事情? 如果有人可以幫助我,我將非常感激!
凡在你的PHP你設置了「名稱「屬性?或者你只是把它關閉 –
你需要使用'dataType:「json」'***或***'$ .parseJSON',而不是兩者。確切地說,你在你的問題中寫的方式應該工作得很好。 –
很可能在你的PHP中有其他的東西返回一個額外的字符,這反過來使你的JSON無效。 –