获取跨源请求被阻止:使用jqgrid时

时间:2015-02-21 22:59:27

标签: php

我正在尝试首次使用jqgrid设置页面。我使用的是一个简单的例子: 的index.php

<?php
 header("Access-Control-Allow-Origin: *");
?>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>My First Grid</title>

<link rel="stylesheet" type="text/css" media="screen" href="css/jquery-ui.css" />
<link rel="stylesheet" type="text/css" media="screen" href="css/ui.jqgrid.css" />

<script type="text/javascript" src="js/jquery-1.11.0.min.js"></script>
<script src="js/grid.locale-en.js" type="text/javascript"></script>
<script src="js/jquery.jqGrid.min.js" type="text/javascript"></script>

<script type="text/javascript">

$(function () {
   $(document).ready(function(){
    $("#list").jqGrid({
        url: 'http://localhost/jqgrid/example.php',
        datatype: "json",
        mtype: "GET",
        colNames: ["First Name", "Last Name", "Equipment Borrowed", "Service Tag", "Reason Borrowed", "Date Taken", "Expected Return Date", "Comments", "ID"],
        colModel: [
            { name: "FName",sortable: false },
            { name: "LName"},
            { name: "Eqpmnt_Brwd", align: "center"},
            { name: "Service_Tag", align: "right",sortable: false },
            { name: "Brwd_Rsn", align: "right", sortable: false },
            { name: "Date_Taken"},
            { name: "Exp_Return"},
            { name: "Comments", sortable: false },
            { name: "id"}
        ],
        pager: "#pager",
        rowNum: 5,
        autowidth: true,
        rownumbers: false,
        rowList: [5, 10, 15],
        sortname: "invid",
        sortorder: "desc",
        viewrecords: true, 
        gridview: true,
        autoencode: true,
        height: 'auto',
        width: '500',
        loadonce: true,
        caption: "Alan's Grid"
    }); 
 }); 
});
</script>

</head>
<body>
    <table id="list"><tr><td></td></tr></table> 
    <div id="pager"></div> 
</body>
</html>

使用example.php:

<?php
ini_set('display_errors',1); 
error_reporting(E_ALL);

//database setting
$dbhost='localhost';
$dbuser='***';
$dbpassword='***';
$database='inventory_form';
$page = $_GET['page'];
// get the requested page
$limit = $_GET['rows'];
// get how many rows we want to have into the grid
$sidx = $_GET['sidx'];
// get index row - i.e. user click to sort
$sord = $_GET['sord']; // get the direction if(!$sidx)
$sidx =1;
// connect to the database
$db = mysql_connect($dbhost, $dbuser, $dbpassword) or die("Connection Error: " . mysql_error());
mysql_select_db($database) or die("Error conecting to db.");
$result = mysql_query("SELECT COUNT(*) AS count FROM Inventory");
$row = mysql_fetch_array($result,MYSQL_ASSOC);
$count = $row['count'];
if( $count > 0 ) {
$total_pages = ceil($count/$limit);
}
else {
$total_pages = 0;
}
if ($page > $total_pages) $page=$total_pages;
$start = $limit*$page - $limit; // do not put $limit*($page - 1)
$SQL = "SELECT * FROM Inventory ORDER BY $sidx $sord LIMIT $start , $limit";
$result = mysql_query( $SQL ) or die("Couldn t execute query.".mysql_error());
$responce->page = $page;
$responce->total = $total_pages;
$responce->records = $count;
$i=0;
while($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
$responce->rows[$i]['id']=$row[id];
$responce->rows[$i]['cell']=array($row[FName],$row[LName],$row[Eqpmnt_Brwd],$row[Service_Tag],$row[Brwd_Rsn],$row[Date_Taken],$row[Exp_Return],$row[Comments],$row[id]);

$i++;
}
echo json_encode($responce);
?> 

我只获取index.php页面上的列标题并查看java控制台我只注意到一个警告

"Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost/jqgrid/example.php?_search=false&nd=1424558292246&rows=5&page=1&sidx=invid&sord=desc. This can be fixed by moving the resource to the same domain or enabling CORS.
http://localhost/jqgrid/example.php?_search=false&nd=1424558292246&rows=5&page=1&sidx=invid&sord=desc
Line 0

阅读CORS我将我的Apache开发服务器设置为a2enmod标头,但仍然收到错误消息。我也尝试了php命令头(等...)但也没有好处。如果可能的话,我更喜欢客户端解决方案。我也知道我应该使用PDO,但我找不到一个例子。即使是jqgrid站点示例也不使用PDO。有关解决此问题的任何建议。

2 个答案:

答案 0 :(得分:0)

原产地的定义 如果协议,端口(如果指定了一个端口)和主机对两个页面都相同,则两个页面具有相同的原点。

  

http://store.company.com/dir2/other.html成功
  http://store.company.com/dir/inner/another.html成功   https://store.company.com/secure.html失败不同的协议   http://store.company.com:81/dir/etc.html失败不同的端口   http://news.company.com/dir/other.html失败不同的主机

您可以使用

更改域名
document.domain = "yourdomain.com";

比启用跨源访问更简单,更安全

答案 1 :(得分:0)

您需要将header("Access-Control-Allow-Origin: https://datasource.com");放在服务器上而不是客户端上。 例 https://origin.com/是您拥有jqgrid的地方 https://datasource.com是您要获取数据的地方。 数据源中的php文件将以

开头
<?php    
header("Access-Control-Allow-Origin: https://origin.com");
header('Access-Control-Allow-Credentials: true');