[英]Separating PHP variables in JSON string
我有點不知道如何解決我的問題。 我在PHP上有一些代碼,它通過一個數組傳遞數據(錯誤,頁面(id,名稱,標題等),並且該數組已使用parseJSON設置。如果我警告響應,我將獲得一個具有正確值的數組但是我的問題是,響應始終是不同的,因此是PHP變量發生了變化。
我已經嘗試了諸如responseText.pageid或responseText.error [1]之類的方法,但由於它可能有所不同,因此無法正常工作。 而且我不知道是否需要將其稱為responseText.pageid,因為在數組中它是$ pageid或其他名稱...
因此,提醒responseText給我一個很好的結果,但是不幸的是,將其分開將無法工作。
我的JS代碼:
// Variables
var content_page = $('#content-page').val();
var content_url = 'action=chose&page='+content_page;
/* Starting AJAX post form */
$.ajax({
type: 'POST',
dataType: "JSON",
url: 'handlers/content.handler.php',
data: content_url,
success: function(responseText)
{
var obj = $.parseJSON(responseText);
console.dir(obj.error);
if(obj.error[1] > -1)
{
noty({ text: 'U hebt geen pagina gekozen!' });
}
else if(obj.error[2] > -1)
{
noty({ text: 'De gekozen pagina bestaat niet!' });
}
else if(obj.error[100] > -1)
{
noty({ text: 'Uw pagina wordt opgehaald...' });
}
}
});
return false;
});
我的PHP代碼:
// Storing the variables.
$stringPage = trim($_POST['page']);
$error = array();
$bolean = false;
// Prepared statement.
$stmt = $mysqli->prepare('SELECT id,name,title,text FROM pages WHERE name = ?');
$stmt->bind_param('s', $stringPage);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($pageID, $pageName, $pageTitle, $pageText);
$stmt->fetch();
$intPage = $stmt->num_rows();
$stmt->close();
# Controle
if(empty($stringPage))
{
$error[] = 1;
$bolean = false;
}
if($intPage == 0)
{
$error[] = 2;
$bolean = true;
}
if($bolean == false)
{
$error[] = 100;
}
header('Content-Type: application/json');
$aVariables = array('error' => $error, 'id' => $pageID, 'name' => $pageName, 'title' => $pageTitle, 'text' => $pageText);
echo json_encode($aVariables, JSON_FORCE_OBJECT);
我已經用Google搜索並得出結論,我需要從parseJSON中創建一個變量,但是不幸的是我沒有任何結果。 我當前的結果( http://prntscr.com/72c39h )正在工作,但是用responseText.home分隔它卻無法工作。
在此先感謝您,並對語法和語言不好我深表歉意!
調用JQuery的parseJSON()
,必須正確調用它,例如$.parseJSON()
,並將其存儲在變量中,例如var obj = $.parseJSON(responseText);
,根據文檔 。
不需要var obj = $.parseJSON(responseText);
,此responseText
已經為json格式。 如果要訪問error
則只需通過responseText.error
或'alert(responseText.error);'引用即可。 並且也不需要設置header('Content-Type: application/json');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.