[英]Getting Ajax requests from php file in a client node.js file
因此,我嘗試獲取AJAX請求,以將值返回到我的node.js客戶端頁面。 它正在與其他端口通信,所以我假設這是引起問題的原因。
我有以下幾點。
client.html文件
socket.on('connect', function(){
var user;
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
user=xmlhttp.responseText;
}
}
xmlhttp.open("GET","http:localhost:80/getUserSession.php",true);
xmlhttp.send();
alert(user);
});
getUserSession.php文件
<?php
header('Access-Control-Allow-Origin: *');
session_start();//start the session
if(isset($_SESSION['username'])){
echo $_SESSION['username'];
}
?>
如果我直接運行http:localhost:80/getUserSession.php
文件,它將回顯currentSession用戶。 但是,使用請求時,它會警告該值未定義。 謝謝謝恩
UPDATE嗨,謝謝您檢查我的日志文件,首先ajax請求確實進入了日志,但是我可以看到它應該是localhost:80時將進入localhost:8080。
這是嘗試執行ajax請求時日志中的內容,請注意localhost:8080
即使我在ajax請求中具有http://localhost:80/getUserSession.php
127.0.0.1 - - [11/Mar/2014:23:02:33 +0000] "GET /getUserSession.php HTTP/1.1" 200 - "`http://localhost:8080/`" "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0"
這是我手動訪問鏈接並查看回顯用戶名時的日志。
127.0.0.1 - - [11/Mar/2014:23:03:19 +0000] "GET /getUserSession.php HTTP/1.1" 200 5 "-" "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0"
如果要從數據庫中回顯用戶名,則不會使用上面列出的node.js文件。
相反,我會做一些不同的事情:
1)創建一個包含對您的'getUserSession.php'進行AJAX調用的常規index.html文件2)創建一個'Config.php'文件,該文件將以所需的值鏈接到您的數據庫3)回顯正在訪問的當前會話用戶您的數據庫。
AJAX調用:
$.ajax(
{
type: "GET",
url: 'getUserSession.php',
datatype: 'json',
success: function (result) {
$("#container").html(result); // '#Container' is a DIV that you will put in your index.html file...This is where the user name will be printed on your webpage.
}
});
Config.php:
<?php
ini_set("display_errors", true);
date_default_timezone_set("America/New_York"); http://www.php.net/manual/en/timezones.php
define( "DB_DSN", "YOUR DATABASE HOST AND DATABASE NAME INFORMATION");
define( "DB_USERNAME", "YOUR USER NAME");
define( "DB_PASSWORD", "YOUR USER PASSWORD");
define("ADMIN_USERNAME", "YOUR ADMIN USER NAME");
define("ADMIN_PASSWORD", "YOUR ADMIN PASSWORD");
function handleException ( $exception) {
echo "Sorry, a problem occurred. Please try later.";
error_log( $exception->getMessage() );
}
set_exception_handler('handleException');
?>
getUserSession.php:
<?php
require("config.php");
session_start();
header('Access-Control-Allow-Origin: *');
echo DB_USERNAME;
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.