【发布时间】:2012-01-16 13:35:18
【问题描述】:
我一直试图弄清楚如何在我的情况下使用 jsonp,但没有运气。这会计算点击次数,并在每次点击时将名称和位置写入 txt 文件。
<script>
var count1 = 0;
function countClicks1() {
count1 = count1 + 1;
document.getElementById("p1").innerHTML = count1;
}
function doAjax()
$.ajax({
type: "POST",
url: "phpfile.php",
data: "name=name&location=location",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
}
document.write('</p>');
document.write('<button onclick="countClicks1(); doAjax();">Count</button>');
document.write('</p>');
document.write('<p id="p1">0</p>');
</script>
这是php文件phpfile.php
<?php
$name = $_POST['name'];
$location = $_POST['location'];
$myFile = "test.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, $name);
fwrite($fh, $location);
fclose($fh);
?>
如果这两个文件在同一个域中,一切都很好。但是如果我想对另一个域做同样的事情,它就行不通了。我想用 jsonp 将相同的信息发送到 phpfile.php。我知道它应该与 GET 一起使用,但我就是不知道怎么做。
【问题讨论】:
-
你可以使用 getJSON : api.jquery.com/jQuery.getJSON
-
请停止使用 document.write。它让我的眼睛受伤......
-
题外话:关于 PHP 代码 - 你确定
fopen($myFile, 'w')是正确的吗?这将打开一个用于写入的文件,并且所有以前的内容都将被覆盖。我想你想改用fopen($myFile, 'a')。这会打开 appending 的文件。 -
我只是使用 txt 文件进行测试。我应该使用什么来代替 document.write?
标签: php javascript jquery jsonp