我已经在脚本中预先定义了所有内容。我想要做的是当我点击提交时,它将在不刷新页面的情况下完成工作。目前它刷新页面并显示“正在工作”。我想做的是这样的事情:
这是我的代码:
<?php
$url="http://google.com";
if(isset($_POST["submit"])){
$ch = curl_init("$url");
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_exec($ch);
$retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if (200==$retcode) {
echo "working";
} else {
echo "failed";
}
}
?>
<form action='ping.php' method='post'><input type="submit" name="submit"></form>
<script src="plugins/jQuery/jquery-2.2.3.min.js"></script>
<script type="text/javascript">
var $url = '<?php echo $url ?>';
$('#submit').click(function(e){
e.preventDefault();
var $this = $(this);
$.get($url,function(data){
$this.text('Success');
});
});
</script>
上例中的脚本显示错误:
[请求]已被CORS策略阻止:请求的资源上没有“Access-Control-Allow-Origin”标头。
所以我打算用PHP cURL来做。如果有人知道任何解决方案,请帮助。
答案 0 :(得分:0)
我不是PHP专家,但我认为这一行
var $url = '<?php echo $url ?>';
将呈现为html为
var $url = 'http://google.com';
这意味着您正在尝试从您自己的域名对Google的网站进行XHR调用。这就是你得到CORS错误的原因。
我认为你实际上是在尝试使用PHP作为代理来与Google沟通(这应该可以正常工作)。
如果上面粘贴的代码名为ping.php
,则<form>
上的操作看起来就像是连接到自身的POST。
您需要做的唯一改变是以下......
<form action='ping.php' method='post'>
<button>PING</button>
</form>
<script type="text/javascript">
// Use the `submit` event on the form instead of the click event on the button.
// It's good practice for this sort of thing.
$('form').on('submit', function(e){
e.preventDefault();
var form = $(this);
var button = form.find('button');
// Set the button text to 'working'
button.text('Working...');
var url = form.attr('action');
$.get(url, function(data) {
button.text('Success');
});
});
</script>
答案 1 :(得分:0)
我不是javascript专家但是当你尝试进行跨域调用时,你应该将dataType设置为jsonp并将crossDomain设置为true。像这样:
$.ajax({
url: 'HTTP://THE_URL',
type: 'GET',
crossDomain: true,
dataType: 'jsonp',
success: function() { alert("Success"); },
});
我可能错了:)
答案 2 :(得分:0)
正如其他人所提到的,访问控制允许来源错误是CORS问题。这是因为AJAX请求指向$ url中的url(即http://google.com
)。相反,请使用$.post()代替$.get()在代码顶部使用curl请求(即if(isset($_POST["submit"])){...
)。帖子的URL应该是PHP页面(即pong.php?)。在下面的代码示例和demo中(请参阅此答案的结尾),它使用PHP_SELF(即$_SERVER['PHP_SELF']
)来发送POST请求的URL。它在POST数据中传递$ url(.post()的第二个参数。另外,我们需要使用.val()来更新按钮的文本(请参阅下面的注释)。
var $url = '<?php echo $_SERVER['PHP_SELF']; ?>';
$('#submit').click(function(e){
e.preventDefault();
var $this = $(this);
$.post($url,{url: "<?php echo $url;?>"}, function(data){
//see note below about using .text()
//$this.text('Success');
$this.val('Success');
});
});
另外,正如我在评论中提到的,没有具有id属性 submit 的元素,因此点击处理程序永远不会被执行。并且为了更新提交按钮上的文本,请为其指定一个值并使用.val()更新该值。
添加 id 和值属性:
<input type="submit" id="submit" name="submit" value="Submit">
在成功回调中使用.val():
$this.val('Success');
参见this PHPFiddle中的演示。
可以使用的另一个可能的功能是.load() - 它仍然容易出现CORS问题,但至少可以调用callback function。