开发者

json_encode issue

开发者 https://www.devze.com 2023-02-13 04:59 出处:网络
i have this code if($_POST){ // response hash $response = array(\'type\'=>\'\', \'message\'=>\'\');

i have this code

    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 assu开发者_如何学JAVAme 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;
}

and i want to redirect to page ( ok.html ) after 'success'. how can i make it

regards


You can redirect the page:

window.location = 'ok.html';

But it is better to change the current page content using javascript.


Redirections in PHP are generally made by using

header("Location: NEWLOCATION");

Where NEWLOCATION is the url to the new page.

This should be called before you output any information on your page, since the headers are always sent before any other content (and cannot be sent afterwards).

If you wish to use the header function even after you have outputted something else, simply save all your output in a variable, so instead of echo("output") do $myvar.="output";

And then, at the end of the file, where you will know if you want to redirect or not, do an echo($myvar);


It does not make any sense to echo something to the browser and then re-direct as the visitor will not see the message anyway.

So you can either:

  1. Not echo / print anything but store the response array in a database or a session variable and then use a php header redirect to go to ok.html;
  2. Use javascript to set a time-out and then redirect using window.location after the timeout.
0

精彩评论

暂无评论...
验证码 换一张
取 消