如何使用反应组件实现json-p

时间:2016-09-07 23:03:22

标签: javascript reactjs jsonp

我正在尝试用React创建一个Wikipedia Viewer。但是,由于交叉原因问题,我无法进行正常的ajax调用以从我的localhost上的Wikipedia API获取数据。 React似乎也不接受jquery($)让我使用jquery JSON-p。我也试过纯粹的javascript方式,但我不确定我是否做错了,它也没用。

有人能告诉我如何从react组件到Wikipedia API进行JSON-p调用吗?

这是我使用的jquery JSOP api调用。

需要来自'jquery'的jquery;

$。当($。AJAX({     url:“https://en.wikipedia.org/w/api.php?action=opensearch&format=json&redirects=return&search=”+ searchTerm,     dataType:'jsonp'   }))   .then(function(result){...

更新: 现在我让jquery在做出反应。我用过 - 从'jquery'导入$。 API调用似乎正在运行。但是,我无法从jquery json-p块中获取数据。它无法识别this.setState或此块之外的任何其他函数。以下是我目前的代码:

import $ from 'jquery';
import React from 'react';
import { render } from 'react-dom';
import Searchbar from './Searchbar';
import ListView from './ListView';

class App extends React.Component {
  constructor(){
    super();
    this.state = {
      term: ""
    };
  }

  searchWiki(term){
    $.when($.ajax({
      url: "https://en.wikipedia.org/w/api.php?action=opensearch&format=json&redirects=return&search="+term,
      dataType: 'jsonp'
    }))
    .then(function(result){
      console.log(result);
      this.setState({term:term});
      });
  }


  render(){


    return(
      <div>
        <center>
          <h1>Wikipedia Viewer</h1>
          <Searchbar onSearchTermChange={this.searchWiki.bind(this)}/>
              <ListView term={this.state.term}/>
        </center>
      </div>
    )
  }
}

render(<App />, document.getElementById('app'))

1 个答案:

答案 0 :(得分:0)

耶!我设法找到了解决这个问题的方法。对于JSON-P jquery,我不得不使用ES6语法(result)=>{}作为'then'回调函数,就像这样

import $ from 'jquery';
import React from 'react';
import { render } from 'react-dom';
import Searchbar from './Searchbar';
import ListView from './ListView';

class App extends React.Component {
  constructor(){
    super();
    this.state = {
      term: "",
      searchResult: ""
    };
  }

  searchWiki(term){

    $.when($.ajax({
      url: "https://en.wikipedia.org/w/api.php?action=opensearch&format=json&redirects=return&search="+term,
      dataType: 'jsonp'
    }))
    .then((result)=>{
        console.log(result[1]);

        this.setState({
          term: term,
          searchResult: result[1]
        });
      });



  }


  render(){


    return(
      <div>
        <center>
          <h1>Wikipedia Viewer</h1>
          <Searchbar onSearchTermChange={this.searchWiki.bind(this)}/>
          <ListView term={this.state.searchResult}/>
        </center>
      </div>
    )
  }
}

render(<App />, document.getElementById('app'))