0

我有一个 javascript 页面,应该将用户输入的用户名发送到服务器上的 php 脚本。javascript 页面来自http://192.168.1.4/login.html,它尝试访问http://192.168.1.4/GetInfo.php的 php 脚本。我认为我无法从 javascript 页面访问 php 脚本中的用户名,因为 firefox 中的相同来源策略但是,我不确定如何确认这种怀疑,所以如果我错了,请原谅我。我才刚刚开始学习 javscript 和 php。我想知道当时是否有不同的方式来传递这些信息。代码如下。谢谢!

的JavaScript:

<html>
    <head>
        <title>Login Page for SplitAuth</title>
    </head>
    <script language="javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
    <script language="Javascript">
        function getUsername()
        {
            var username = window.prompt('Please Type Your Username');
            var temp = document.getElementById('temp');
            temp.innerHTML = username;
            jQuery.ajax(
                {
                    type: "POST",
                    url:"GetInfo.php",
                    data: username,
                    success: function(msg)
                            {alert("data Saved: "+msg);}

                });//ends the jQuery send

        }//ends the GetUsername function
    </script>
    <body onLoad=getUsername()>
        <div id="temp">This will show text</div>
    <body>

</html>

php脚本:

<?
$inFile="MyID.config.php";
$handle=fopen($inFile, 'r') or die ("No credentials could be gotten because the file MyID.config.php would not open.");

echo $_POST['msg'];

fclose($fh);

?>
4

3 回答 3

3

你应该在你的前面加上data:“msg =”。

...
data: "msg="+username,
...

原因是jQuery.ajax需要一个查询字符串或一个对象,这意味着

...
data: {msg: username},
...

也可以。

查看jQuery.ajax 文档。特别是data-section

于 2012-04-20T21:55:55.603 回答
0

您正在使用 POST 方法并且您发送的数据是错误的。您需要构建要发送的数据。看看 ajax 方法中的 jquery 页面。这就是它对数据属性的说法。

http://api.jquery.com/jQuery.ajax/

要发送到服务器的数据。如果还不是字符串,则将其转换为查询字符串。它附加到 GET 请求的 url。请参阅 processData 选项以防止此自动处理。对象必须是键/值对。如果 value是一个 Array,jQuery 根据传统设置的值(如下所述)序列化具有相同键的多个值。

于 2012-04-20T21:57:59.353 回答
-1

您的脚本应如下所示。

 $.ajax({
  type: "POST",
  url: "GetInfo.php",
  data: "{name:"+ username + "}"
  }).done(function( msg ) {
 alert( "Data Saved: " + msg );
 });

并且您的 php 脚本没有获取用户名值。$_POST['msg'] 中使用的“msg”不会发出任何警报,因为它没有任何价值。“msg”变量用于将返回值的值存储到您的 html 页面。我会建议你从 www.jquery.com 阅读更多内容

于 2012-04-20T22:24:06.620 回答