如何使用javascript将json数据从一个html页面传递到另一个html页面?

时间:2015-02-12 04:36:40

标签: javascript php jquery json

我必须传递将信息插入数据库表后生成的Json数据,现在我必须将此信息传递给其他页面 BookingConformation.html

例如我们将获得表单服务器欢迎Mr / Mrs Mittel感谢预订家庭服务您的预订ID为1。所以请告诉我如何在javascript中传递获取表单服务器的信息我必须将此信息传递给其他页面,请帮助我。

脚本

<script>
    $(document).ready(function(){
        $("#register-form").validate({
            rules: {
                userName: "required",                           
                email: {
                    required: true,
                    email: true
                },                                              
                userContactNumber: "required"                       
            },
            messages: {
                userName: "Please enter your Name",
                userContactNumber: "Please enter your Mobile number",                           
                email: "Please enter a valid email address",                                           
            },
            submitHandler: function(form) {

                var uName = $('#userName').val();   
                var mailId = $('#email').val();                 
                var mobNum = $('#userContactNumber').val();

                $.ajax({                
                    url:"http://localhost/bookRoom/book.php",
                    type:"POST",
                    dataType:"json",
                    data:{type:"booking", Name:uName, Email:mailId,  Mob_Num:mobNum},                                   
                    ContentType:"application/json",
                    success: function(response){
                    //alert(JSON.stringify(response));
                    //alert("success");                     
                    alert(response);
                    var globalarray = [];
                    globalarray.push(response);
                    window.localStorage.setItem("globalarray", JSON.stringify(globalarray));
                    window.location.href = 'BookingConformation.html';
                },
                    error: function(err){                           
                        window.location.href = 'error.html';
                    }
                });
                return false; // block regular submit
            }
        });
    });
</script>

服务器代码

    <?php
    header('Access-Control-Allow-Origin: *');//Should work in Cross Domaim ajax Calling request
    mysql_connect("localhost","root","7128");
    mysql_select_db("service");

    if(isset($_POST['type']))
    {
        if($_POST['type']=="booking"){
            $name = $_POST ['Name'];    
            $mobile = $_POST ['Mob_Num'];
            $mail = $_POST ['Email'];               
            $query1 = "insert into customer(userName, userContactNumber, email) values('$name','$mobile','$mail')";
            $query2 = "insert into booking(cust_email, cust_mobile, cust_name) values('$mail','$mobile','$name')";          

            $result1=mysql_query($query1);          
            $result2=mysql_query($query2);
            $id=mysql_insert_id();
            $value = "Welcome Mr/Mrs ".$name."  Thanks for booking home services your booking id is =  ".$id;
            echo json_encode($value);
        }
    }
    else{
        echo "Invalid format";
    }
?>

BookingConformation.html

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript">
            function myFunction() {
                 var globalarray = [];
                 var arrLinks =[];
                 arrLinks = JSON.parse(window.localStorage.getItem("globalarray"));
                 document.getElementById("booking").innerHTML = arrLinks;
             }
        </script>
    </head>
    <body>  
        <p id="booking" onclick="myFunction()">Click me to change my HTML content (innerHTML).</p>
    </bod

Y'GT;

3 个答案:

答案 0 :(得分:1)

如果这是你真正的服务器端代码那么......它完全不安全。您永远不应将用户发布的变量直接传递给您的查询。

$query2 = "insert into booking(cust_email, cust_mobile, cust_name) values('$mail','$mobile','$name')";  

至少使用“mysql_real_escape_string”转义值,或使用预准备语句。并且......不再使用mysql,使用mysqli,它几乎与您使用的相同,但不会很快弃用。

另外,你是json编码一个不需要json编码的字符串,它只是一段文本而不是有效的json代码。这可能就是为什么@SimarjeetSingh Panghlia的答案对你不起作用的原因。

而不是json_encoding该值,编码结构化数组。

$response = array( "status" => true );

if(isset($_POST['type']))
    {
        if($_POST['type']=="booking"){
            $name = mysql_real_escape_string( $_POST ['Name'] ));    
            $mobile = mysql_real_escape_string($_POST ['Mob_Num']);
            $mail = mysql_real_escape_string($_POST ['Email']);               
            $query1 = "insert into customer(userName, userContactNumber, email) values('$name','$mobile','$mail')";
            $query2 = "insert into booking(cust_email, cust_mobile, cust_name) values('$mail','$mobile','$name')";          

            $result1 = mysql_query($query1);          
            $result2 = mysql_query($query2);
            $id = mysql_insert_id();

            $response["message"] = "Welcome Mr/Mrs ".$name."  Thanks for booking home services your booking id is =  ".$id;/* make sure you strip tags etc to prevent xss attack */

        }
    }
    else{
        $response["status"] = false;
        $response["message"] = "Invalid format";
    }

    echo json_encode($response);

    /* Note that you are making the query using ContentType:"application/json", */

这意味着无论查询是否成功,您都应该使用json进行响应。我还建议使用一个名为jStorage的简单jQuery插件,它允许轻松获取/设置对象而无需序列化它们。

答案 1 :(得分:0)

你可以试试这个

在第一页声明变量

<script type="text/javascript">
    var globalarray = [];
    globalarray.push(response.d);
     window.localStorage.setItem("globalarray", JSON.stringify(globalarray));
</script>

在第二页上调用该变量

<script type="text/javascript">
         var globalarray = [];
         var arrLinks =[];
         arrLinks = JSON.parse(window.localStorage.getItem("globalarray"));
        console.log(arrLinks);
</script>

答案 2 :(得分:0)

您可以使用sessionStorage来存储和检索JSON数据。

var complexdata = [1, 2, 3, 4, 5, 6];

// store array data to the session storage
sessionStorage.setItem("list_data_key",  JSON.stringify(complexdata));

//Use JSON to retrieve the stored data and convert it 
var storedData = sessionStorage.getItem("complexdata");
if (storedData) {
  complexdata = JSON.parse(storedData);
}

使用sessionStorage.clear();

后删除sessionStorage数据