我尝试使用网络语音API从Google动态收集一些免费图片。
这是逻辑:
如果关键字只是一个单词,如:Barack,那么一切正常,但如果我使用Barack Obama,则会出现500服务器错误并且ajax调用失败。
的JavaScript
$keyword = 'Barack Obama'; //the $Keyword is created from the result of the Web Speech API, but to make this clearer I just created it manually bc the problem still there anyway.
$.ajax({
type:'POST',
url: '../php/myfunctions.php',
data: {$keyword:$keyword},
dataType:"json",
}).done(function(response) {
console.log('yeah');
})
.fail(function(responseText) {
console.warn('error: ',responseText);
});
PHP
include_once($_SERVER['DOCUMENT_ROOT'].'/php/library/simple_html_dom.php');
$keyword = $_POST['$keyword'];
$keyword = 'Barack Obama'; //IF I manually create the $keyword all is fine but It's not the idea so this line is just to debug this issue.
$keyword = strtolower($keyword); //I tried with lowercases (barack obama).
$keyword = rawurlencode($keyword); //Then I tried a encoding workaround (barack%20obama).
$keyword = str_replace(' ','',$keyword); //Then I tried without white spaces(barackobama).
$url = 'https://www.google.com/search?q=' . $keyword . '&tbm=isch&source=lnt&tbs=sur:fc&sa=X&ved=0ahUKEwjQgMn87ajaAhUOtlkKHdgZB_8QpwUIHg&biw=1745&bih=872&dpr=1.1';
$html = file_get_html($url);
//From here I handle this data and I send it back in a json to JS
echo $url //if I echo the $url these are the outputs:
https://www.google.com/search?q=barack obama&tbm=isch&source=lnt&tbs=sur:fc&sa=X&ved=0ahUKEwjQgMn87ajaAhUOtlkKHdgZB_8QpwUIHg&biw=1745&bih=872&dpr=1.1
https://www.google.com/search?q=barack%20obama&tbm=isch&source=lnt&tbs=sur:fc&sa=X&ved=0ahUKEwjQgMn87ajaAhUOtlkKHdgZB_8QpwUIHg&biw=1745&bih=872&dpr=1.1
https://www.google.com/search?q=barackobama&tbm=isch&source=lnt&tbs=sur:fc&sa=X&ved=0ahUKEwjQgMn87ajaAhUOtlkKHdgZB_8QpwUIHg&biw=1745&bih=872&dpr=1.1
如果我手动将这3个URL复制并粘贴到浏览器中,则没有问题,所有图像都会出现,但如果在JS中创建的$关键字有2个单词,如纽约则会出现500错误。
可能是什么问题?问候。
答案 0 :(得分:1)
而不是
need
使用
data: {$keyword: $keyword}
然后删除data: {keyword: encodeURIComponent($keyword)}
因为你肯定没有在那里回应json。