我有一个 HTML 页面,它将 JSON 信息发布到服务器。
如果服务器认为发布的信息有错误,它会返回一个 JSON 字符串,以便客户端可以修改当前的 HTML 页面并显示错误消息。
否则,服务器将返回一个新的 HTML 页面。
如何在 jQuery 中处理这个问题?
最佳答案
好吧,那么你可以将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);
}
});
关于javascript - jQuery - 使用 JSON 进行发布并接收 JSON 和 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22123319/