2011-12-09 38 views
1

我一直想弄清楚如何在我的情况下使用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,但我不知道如何。

+0

这不是JSONP。 –

+0

您可以使用getJSON:http://api.jquery.com/jQuery.getJSON/ –

+0

请停止使用document.write。它使我的眼睛受伤... –

回答

1

首先,你的php文件不会输出任何东西,所以我根本不会调用这个JSONP。 JSONP是一种使用GET请求获取JSON数据的方法,该请求返回一个可以使用<SCRIPT>标记加载的Javascript块。

对于做JSONP你自己,你必须做这样的事情:

<?php 
$callback = $_GET['callback']; 
$name = $_GET['name']; 
$location = $_GET['location']; 
$myFile = "test.txt"; 
$fh = fopen($myFile, 'w') or die("can't open file"); 
fwrite($fh, $name); 
fwrite($fh, $location); 
fclose($fh); 
header("Content-Type: application/javascript"); 
?> 

<?php echo $callback; ?>("Message from the server"); 

然后执行调用是这样的:

$.getJSON("http://server/phpfile.php?name=FOO&location=BAR&callback=?", 
      function(message) { 
       alert(msg); 
      }); 

但是...既然你不实际上不会从服务器返回任何数据,只需使用正确的URL伪造图像即可。这将大大减少开销。

+0

谢谢你的帮助! – Ciprian

+0

如何从服务器返回数据?我想检查用户是否登录 – Ciprian