Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ajax/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript React—从Ajax post请求的响应元数据元素中获取“消息”_Javascript_Ajax_Reactjs - Fatal编程技术网

Javascript React—从Ajax post请求的响应元数据元素中获取“消息”

Javascript React—从Ajax post请求的响应元数据元素中获取“消息”,javascript,ajax,reactjs,Javascript,Ajax,Reactjs,因此,我收到了来自Ajax post请求的响应。响应的一部分显示在以下位置: Data: Meta-Data: Topic : "Sign-Up" Message : "Already in the System!" Response Code : "650" . . . 如何获取消息并将其显示给用户?我在想,我可以这样做: state = { username : "John", password : "somePass", p

因此,我收到了来自Ajax post请求的响应。响应的一部分显示在以下位置:

Data:
  Meta-Data:
    Topic : "Sign-Up"
    Message : "Already in the System!"
    Response Code : "650"
.
.
.  
如何获取消息并将其显示给用户?我在想,我可以这样做:

    state = {
    username : "John",
    password : "somePass",
    postResponse : null
    }
    axios.post(URL, JSON.stringify({ username : this.state.username , password: this.state.password})
    .then(response => { this.setState({postResponse : response.data}) }
然后在渲染中,我会:

     render(){
let message = null; 
    if (this.state.postResponse){
    message = <p>{this.postResponse.data.meta-data.message}</p> //apparently the dash is breaking the code!
    }
     return(<div> {message} </div>)}
这根本不起作用!
这是我代码的一部分,我希望我已经包含了所有必要的部分,我可以看到两件事。你有这个。回复。据我所知,应该是this.state.postResponse。此外,您需要将“元数据”放在引号中,并使用括号来引用它,如下所示

state = {
    username : "John",
    password : "somePass",
    postResponse : null
    }
    axios.post(URL, JSON.stringify({ username : this.state.username , password: this.state.password})
    .then(response => { this.setState({postResponse : response.data}) }

render(){
  let message = null; 
  if (this.state.postResponse){
    message = <p>{this.state.postResponse[“meta-data”].message}</p>
    }
     return(<div> {message} </div>)}

非常感谢。我也不知道我可以要求后端程序员将元数据更改为元数据以使工作更简单,但我只是想出来了。是的,好主意。这让事情变得容易多了。另外,我不确定它是否对您有多重要,但我注意到,如果您要直接从axios响应引用元数据,它将是response.data.data.metaData。如果很容易更改,则可能值得使用另一个键而不是数据(如“body”),以避免混淆,即response.data.body.metaData。