Php json_编码问题
我有这个密码Php json_编码问题,php,ajax,Php,Ajax,我有这个密码 if($_POST){ // response hash $response = array('type'=>'', 'message'=>''); try{ // do some sort of data validations, very simple example below $required_fields = array('name'); foreach($required_f
if($_POST){
// response hash
$response = array('type'=>'', 'message'=>'');
try{
// do some sort of data validations, very simple example below
$required_fields = array('name');
foreach($required_fields as $field){
if(empty($_POST[$field])){
throw new Exception('field is empty');
}
}
// ok, field validations are ok
// now add to data to DB, Send Email, ect.
// let's assume everything is ok, setup successful response
$response['type'] = 'success';
$response['message'] = "Done";
}catch(Exception $e){
$response['type'] = 'error';
$response['message'] = $e->getMessage();
}
// now we are ready to turn this hash into JSON
print json_encode($response);
exit;
}
我想在“成功”之后重定向到页面(ok.html)。我怎样才能做到
关于您可以重定向页面:
window.location = 'ok.html';
但是最好使用javascript更改当前页面内容。PHP中的重定向通常通过使用
header("Location: NEWLOCATION");
其中NEWLOCATION是指向新页面的url
在页面上输出任何信息之前应该调用此函数,因为标题总是在任何其他内容之前发送(并且不能在之后发送)
如果您希望在输出其他内容后仍使用header函数,只需将所有输出保存在一个变量中,这样就不用echo(“output”)而使用$myvar.=“output”
然后,在文件末尾,您将知道是否要重定向,执行echo($myvar) 将某些内容回显到浏览器,然后重新定向是没有任何意义的,因为访问者无论如何都看不到消息 因此,您可以:
ok.html
李>
window.location
重定向返回JSON时,为什么要重定向到HTML页面?我不明白。我猜您希望在成功消息后使用
window.location
从客户端重定向returned@Pekka,因为Pin Cody不了解HTTP的基本原理。一旦使用print(json_encode())
输出json字符串,就不能继续使用PHP重定向。PHP已经发送了它的头,并且不允许您使用头重定向(“位置:http://example.com/ok.html");
如果已经输出JSON,则必须按照建议在客户端使用javascript完成。@Pin Cody-您可以发送有关页面重定向的JSON信息。