我一直想弄清楚如何在我的情况下使用jsonp,但没有运气。这将对点击进行计数,并在每次点击时将名称和位置写入txt文件。用jsonp发送数据onclick
<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,但我不知道如何。
这不是JSONP。 –
您可以使用getJSON:http://api.jquery.com/jQuery.getJSON/ –
请停止使用document.write。它使我的眼睛受伤... –