尝试使用网络语音 API 从 Google 图像获取内容时出现 500 服务器错误

500 Server error when try to get content from Google Images using Web Speech API

我正在尝试使用网络语音 API 从 Google 动态收集一些免费图像。

逻辑如下:

  1. 我用JS中的Web SpeechAPI抓取搜索关键词
  2. 我使用 ajax 调用
  3. 将其发送到服务器 (PHP)
  4. 然后我处理关键字并将结果发送回JS。

如果关键字只是一个单词,一切正常,例如: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 中创建的 $keyword 有 2 个单词,如 New York,则会出现 500 错误。

可能是什么问题?你好。

而不是

data: {$keyword: $keyword}

使用

data: {keyword: encodeURIComponent($keyword)}

并删除 dataType: 'json',因为您绝对不会在那里回应 json。