将javascript输出写入服务器上的文件

时间:2012-06-28 08:43:24

标签: javascript ajax

所以我有这个HTML文件来测试用户的屏幕分辨率,以及使用Javascript安装的插件。因此,当用户访问它看到的页面时:(例如)您当前的屏幕分辨率为1024x768,并且您安装了以下插件:插件No.2- Java Deployment Toolkit 7.0.10.8 [位置:npdeployJava1.dll],插件在No.3-Java(TM)平台SE 7 U1 [位置:npjp2.dll],插件No.4- Microsoft Office 2003 [位置:NPOFFICE.DLL] ...我还需要将此信息保存在服务器上的文件。所有用户都有firefox或chrome。我如何使用AJAX做到这一点?

<html>
<body>
<script language="JavaScript1.2">
document.write("Your current resolution is "+screen.width+"*"+screen.height+"")
</script>
<BR><BR>
<SCRIPT LANGUAGE="JavaScript">
var num_of_plugins = navigator.plugins.length;
for (var i=0; i < num_of_plugins; i++) {
var list_number=i+1;
document.write("<font color=red>Plug-in No." + list_number + "- </font>"+navigator.plugins[i].name+" <br>[Location: " + navigator.plugins[i].filename + "]<p>");
}
</script>
</body>
</html>

由于

3 个答案:

答案 0 :(得分:6)

没有jQuery(原始JavaScript):

    var data = "...";// this is your data that you want to pass to the server (could be json)
    //next you would initiate a XMLHTTPRequest as following (could be more advanced):
    var url = "get_data.php";//your url to the server side file that will receive the data.
    var http = new XMLHttpRequest();
    http.open("POST", url, true);

    //Send the proper header information along with the request
    http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    http.setRequestHeader("Content-length", params.length);
    http.setRequestHeader("Connection", "close");

    http.onreadystatechange = function() {//Call a function when the state changes.
        if(http.readyState == 4 && http.status == 200) {
            alert(http.responseText);//check if the data was received successfully.
        }
    }
    http.send(data);

使用jQuery

$.ajax({
  type: 'POST',
  url: url,//url of receiver file on server
  data: data, //your data
  success: success, //callback when ajax request finishes
  dataType: dataType //text/json...
});

我希望这会有所帮助:)

更多信息:

答案 1 :(得分:1)

你知道jQuery吗?使用jQuery会更容易。

var data = "";
for (var i=0; i < num_of_plugins; i++) {
   var list_number=i+1;
   document.write("<font color=red>Plug-in No." + list_number + "- </font>"+navigator.plugins[i].name+" <br>[Location: " + navigator.plugins[i].filename + "]<p>");
   data += "<font color=red>Plug-in No." + list_number + "- </font>"+navigator.plugins[i].name+" <br>[Location: " + navigator.plugins[i].filename + "]<p>"; 
}

$.post('savedata.php', {data=data}, function(){//Save complete});

然后在savedata.php中,您可以编写如下内容:

$data = $_POST['data'];
$f = fopen('file', 'w+');
fwrite(f, $data);
fclose($f);

答案 2 :(得分:0)

从javascript向运行服务器端代码的页面发出请求。

使用ajax http://www.javascriptkit.com/dhtmltutors/ajaxgetpost.shtml发送帖子请求,例如apsx页面。从aspx中,您可以将其保存到文本文件或数据库中。