繁体   English   中英

Ajax从React调用到PHP文件

[英]Ajax Call from React to a PHP file

我试图从我的react组件到一个php文件进行ajax调用,我希望php文件返回一个特定的输出,但我得到一个完整的源代码。 有人可以帮忙吗?

这就是我对反应组件的看法。

import React from 'react';
import {Link} from 'react-router';


export default class BikePage extends React.Component {
    onFormSubmitSuccess(e) {
      e.preventDefault();
    $.ajax({
      url: 'php/new_user.php',
      type: "GET",
      success: function(data) {
        console.log('success')
        console.log(data);
      }.bind(this),
      error: function(xhr, status, err) {
        console.log('error')
      }.bind(this)
    });
  }

  render(){
    return (
      <button onClick={this.onFormSubmitSuccess.bind(this)} >click here</button>
    )
  }
}

这是我的PHP文件的最新消息。

<?php
//Function to check if the request is an AJAX request
$return = 'hello'
echo json_encode($return);
?>

我试图测试的是在我的控制台上获取“Hello”。 但相反,我得到了整个php文件。

首先,'hello'不是json可编码的,你需要使用例如array('result'=>'hello')。

如果你获得php文件的内容,似乎你不使用工作的本地服务器。

您需要在PHP设置header以发送JSON结果

尝试这个

<?PHP
$data = 'hello'
header('Content-Type: application/json');
echo json_encode($data);
?>

在您的情况下,您在PHP中使用json_encode()来获取响应,而不是使用DataType:json ,您只需要将DataType用作json,如:

dataType: "json",

您的json输出应该如下所示: "message"

修改后的Ajax:

$.ajax({
url: 'php/new_user.php',
type: "GET",
dataType: "json",
success: function(data) {
    console.log('success');
    console.log(data); // will print "message"
}.bind(this),
error: function(xhr, status, err) {
    console.log('error');
}.bind(this)
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM