我有一个HTML页面,它将JSON信息发布到服务器。
如果服务器认为发布的信息有错误,它会返回一个JSON字符串,以便客户端可以修改当前的HTML页面并显示错误消息。
否则,服务器返回一个新的HTML页面。
我如何在jQuery中处理这个?
答案 0 :(得分:1)
这是不好的做法,但您可以尝试解析回复:
$.ajax({ url: " ....URL...." , type:"POST" , data:{.. your variables ..} })
.done(function(response) {
var tryRes = false;
try { response = $.parseJSON(response); tryRes = true; }
catch (e) { }
if (tryRes) {
//JSON ~ resonse is allready an object
} else {
//OTHER ~ HTML
}
}).fail(function(response) {
//Bad request
});
答案 1 :(得分:1)
那么,你可以把html页面内容放到一个json变量中,然后仍然把它作为json返回。这样你就会继续练习。
示例:
PHP伪代码:
if($ok) //you condition here
{
$html = file_get_contents("newPage.php");
$toEcho = array("status"=>"true" , "message"=>"successful", "html"=>html);
$json_parsed = JOSN_encode($toEcho);
echo $json_parsed;
}
else
{
$toEcho = array("status"=>"false" , "message"=>"Wrong information", "html"=>false);
$json_parsed = JOSN_encode($toEcho);
echo $json_parsed;
}
JS伪代码:
$.ajax({
url: "yourUrl.php",
type: "post",
data:"json"
}).done(function (result){
if(result.status==="true")
{
if(result.html)
{
$("#oldDiv").html(result.html);
}
}
else if(result.message)
{
$("#errorMsg").html(result.message);
}
});