几个小时以来,我一直在努力解决这个问题,尽管我在 Web 开发方面没有受过多少教育,无法理解。情况如下:
另一个网站有一个脚本,他们通过以下方式获取信息:
var url = "numbers.php";
parameters = "scoreid=" + document.getElementById('whatscore').value;
parameters += "&num=" + document.getElementById('num1b1').value;
xmlhttp2=GetXmlHttpObject();
if (xmlhttp2==null) {
alert ("Your browser does not support XMLHTTP!");
return;
}
xmlhttp2.onreadystatechange = function() {
if (xmlhttp2.readyState==4) {
scorespot.innerHTML=xmlhttp2.responseText; // load
setScores(document.getElementById('gradelvl').value); // set
document.getElementById('submitscorebtn').style.display="none";
}
}
xmlhttp2.open("POST",url,true);
xmlhttp2.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp2.setRequestHeader("Content-length", parameters.length);
xmlhttp2.setRequestHeader("Connection", "close");
xmlhttp2.send(parameters);
我曾尝试做同样的事情,但当我尝试这样做时,我遇到了跨域错误。我知道他们是用 jsonp 和其他东西来做到这一点的方法,尽管我完全不知道从哪里开始。
当我尝试直接从他们的页面请求信息时,numbers.php 页面,例如 example.com/numbers.php?scoreid=131&num=41 。我总是返回“错误:不正确的参数语法”。
任何人都可以告诉我如何解决我的情况吗?我只知道 PHP 和 Javascript,我对 Ajax 和其他东西或外部库一无所知。
我感谢所有帮助! 注意:我无权访问网络服务器。
最佳答案
如果您无权访问您的服务器配置,并且您不控制外部 php 脚本(假设它没有设置为用作反向代理),那么您绝对不能使用独立 javascript 解决方案。
相反,您必须从您自己的本地 php 脚本发出外部请求。然后您将从 Ajax 调用您的本地 php 脚本,这将工作,因为您正在访问本地文件,因此不会违反 CORS。
这是一个通过本地 PHP 脚本调用 Ajax 的示例。
想象一下您允许用户查找相册名称的场景。用户输入歌曲名称和艺术家。您向第三方 api 发出请求,并通过 JavaScript 警报通知将响应返回给用户。对于此示例,假设用户输入“Black”和“Pearl Jam”作为歌曲和艺术家名称
使用 HTML 示例将 Ajax POST 发送到本地 PHP 脚本:
<html>
<head>
<!-- Load jQuery Library from Google -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script>
</head>
<body>
<h1> Ajax to local PHP Script Example: </h1>
<form id="getArtist">
Artist: <input type="text" placeholder="Pearl Jam">
Song: <input type="text" placeholder="Black">
<input type="submit" value="Click Here to Active Ajax Call">
</form>
</body>
</html>
<script type='text/javascript'>
$("#getArtist").submit(function(event) { //Listen to when the Submit is pressed
event.preventDefault(); //Stop the submit from actually performing a submit
$.post("local_script.php", { song: "Black", artist: "Pearl Jam", dataType: "json"}) //prepare and execute post
.done(function(response) { //Once we receive response from PHP script
//Do something with the response:
alert("The album name is: " +response);
//Look into JSON.parse and JSON.stringify for accessing data
});
});
</script>
PHP 获取
<?php
$url = 'http://api.music.com/album';
$song = urlencode($_GET['song'])); //Need to url encode
$artist = urlencode($_GET['artist']); //Need to url encode
$response = file_get_contents($url .'?song=' .$song .'&artist=' .$artist);
//**The url looks like http://api.music.com/album?song=Black&artist=Pearl+Jam
//** For purposes of this demo, we will manually assume the JSON response from the API:
$response = '{ "album": "Ten" }'; //(Raw JSON returned by API)
echo $response; //Return the response back to AJAX, assuming it is already returned as JSON. Else encode it json_encode($response)
PHP POST(使用 curl)
<?php
$url = 'http://api.music.com/album';
$song = urlencode($_GET['song'])); //Need to url encode
$artist = urlencode($_GET['artist']); //Need to url encode
//$headers = array("Key: " ."Value","Key: " ."Value", //Set any headers, if required.
$post = 'song=' .$song .'&artist=' .$artist; //Prepare Post parameters
/* Configure Curl */
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //Allow music api to send response
curl_setopt($ch, CURLOPT_POST, 1); //Signifyd that we are doing a POST request
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
//curl_setopt($curl, CURLOPT_HTTPHEADER, $header); //Only if you need to send headers
/* Get Response */
$response = curl_exec($ch);
//** For purposes of this demo, we will manually assume the JSON response from the API:
$response = '{ "album": "Ten" }'; //(Raw JSON returned by API)
echo $response; //Send response back to Ajax, assuming it was already returned in JSON. Else encode it.
进一步阅读 Ajax 请求:
https://api.jquery.com/jquery.get/
https://api.jquery.com/jquery.post/
关于javascript - 使用 PHP 和 Javascript/Ajax 绕过 CORS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29837162/
我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div
我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看rubyzip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d
类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc
很好奇,就使用rubyonrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提
假设我做了一个模块如下:m=Module.newdoclassCendend三个问题:除了对m的引用之外,还有什么方法可以访问C和m中的其他内容?我可以在创建匿名模块后为其命名吗(就像我输入“module...”一样)?如何在使用完匿名模块后将其删除,使其定义的常量不再存在? 最佳答案 三个答案:是的,使用ObjectSpace.此代码使c引用你的类(class)C不引用m:c=nilObjectSpace.each_object{|obj|c=objif(Class===objandobj.name=~/::C$/)}当然这取决于
我正在尝试使用ruby和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。
我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t
我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h
我想为Heroku构建一个Rails3应用程序。他们使用Postgres作为他们的数据库,所以我通过MacPorts安装了postgres9.0。现在我需要一个postgresgem并且共识是出于性能原因你想要pggem。但是我对我得到的错误感到非常困惑当我尝试在rvm下通过geminstall安装pg时。我已经非常明确地指定了所有postgres目录的位置可以找到但仍然无法完成安装:$envARCHFLAGS='-archx86_64'geminstallpg--\--with-pg-config=/opt/local/var/db/postgresql90/defaultdb/po