简体   繁体   English

Ajax从React调用到PHP文件

[英]Ajax Call from React to a PHP file

I am trying to make an ajax call from my react component to a php file in which I am expecting the php file to return a specific output but instead I get an entire source code. 我试图从我的react组件到一个php文件进行ajax调用,我希望php文件返回一个特定的输出,但我得到一个完整的源代码。 Can someone help? 有人可以帮忙吗?

This is what I have on my react component. 这就是我对反应组件的看法。

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>
    )
  }
}

This is whats on my php file. 这是我的PHP文件的最新消息。

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

All I am trying to test is to get the "Hello" on my console. 我试图测试的是在我的控制台上获取“Hello”。 but instead I get the entire php file. 但相反,我得到了整个php文件。

First of all 'hello' is not json encodable you need to use for example array('result' => 'hello'). 首先,'hello'不是json可编码的,你需要使用例如array('result'=>'hello')。

If you gets php file's content it seems that you don't use working local server. 如果你获得php文件的内容,似乎你不使用工作的本地服务器。

You need to set header in your PHP to send JSON results 您需要在PHP设置header以发送JSON结果

Try this 尝试这个

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

In your case, you are using json_encode() in PHP for getting response, and not using DataType:json , you just need to use DataType as json like: 在您的情况下,您在PHP中使用json_encode()来获取响应,而不是使用DataType:json ,您只需要将DataType用作json,如:

dataType: "json",

Your json output should be looks like: "message" 您的json输出应该如下所示: "message"

Modified Ajax: 修改后的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