ReactJs Ajax获取

问题描述:

我想要获得一个正常的ajax获取调用在一个按钮的onClick的reactJs组件内执行。当我尝试使用下面的代码时,什么都没有发生,但api是活的并且正在工作。它甚至不会将任何内容记录到浏览器控制台。我做错了什么?我是新来的,所以我很抱歉。我正在使用reactJS.net与mvc 5和web api 2.我只是看到我是否可以通过它的路线击中webapi v2函数。这条路线本身的工作对自己很好,我能够触发破发点,但不能从reactJs onClick事件ReactJs Ajax获取

var HomeReact = React.createClass({ 
getInitialState: function() { 
    return { 
     welcomeMsg: this.props.welcomeMsg, 
    }; 
}, 

testApi: function() { 
    console.log("Clicking"); 
    $.ajax({ 
     url: "/api/reg/testapi", 
     type: 'GET', 
     cache: false, 
     dataType: 'json', 
     success: function (response) { 
      alert(response) 
     }, 
     error: function (error) { 
      alert("fail - " + error); 
     } 

    }); 
}, 

render() { 
    return (
     <div id="welcomeHolder" align="center"> 
      {this.state.welcomeMsg} 
      <br /> 
      <button onClick={this.testApi}>React Learning Api Test</button> 
     </div> 
    ); 
} 

});

+0

'的console.log( “点击”);'是在控制台上打印点击? –

+0

尝试'onClick = {this.testApi.bind(this)}' –

+0

不幸的是没有打印到控制台。 – Frijx

你的API有些问题。如果您使用工作网址"https://facebook.github.io/react-native/movies.json",,它会起作用。

class Test extends React.Component { 
 
\t \t constructor(props){ 
 
    \t super(props); 
 
     
 
     this.state = { 
 
     \t welcomeMsg: "Welcome message" 
 
     } 
 
    } 
 
    
 
    testApi(){ 
 
     $.ajax({ 
 
      url: "https://facebook.github.io/react-native/movies.json", 
 
      type: 'GET', 
 
      cache: false, 
 
      dataType: 'json', 
 
      success: function (response) { 
 
     \t \t \t \t console.log(response); 
 
      }, 
 
      error: function (error) { 
 
       alert("fail - " + error); 
 
      } 
 

 
     }); 
 
    } 
 
    
 
\t \t render(){ 
 
    \t return (
 
     \t <div id="welcomeHolder" align="center"> 
 
      {this.state.welcomeMsg}<br /> 
 
      <button onClick={this.testApi.bind(this)}>React Learning Api Test</button> 
 
     </div> 
 
    ) 
 
    } 
 
} 
 

 
React.render(<Test />, document.getElementById('container'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react-dom.min.js"></script> 
 
<div id="container"> 
 
    <!-- This element's contents will be replaced with your component. --> 
 
</div>

Here is the fiddle link.

+0

不幸的是,这也不起作用,这是一个.net问题,我很确定它。因为我从上面的代码片段中使用的代码返回的文档错误是未定义的。我很确定它与MVC有关,而且我在mvc视图中呈现了这个反应 – Frijx

在这种情况下,你必须给在Ajax调用 这样

URL完整的URL: “http://localhost:666/api//reg/testapi”,