2016-11-01 65 views
0

我想從我的反應組件到一個PHP文件,我期待PHP文件返回一個特定的輸出,而是我得到一個完整的源代碼的ajax調用。有人可以幫忙嗎?Ajax從React調用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); 
?> 

我試圖測試的是我的控制檯上的「你好」。但是我得到了整個php文件。

回答

0

在你的情況,你是在PHP中使用json_encode()爲獲得迴應,而不是使用DataType:json,你只要需要使用數據類型爲像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) 
}); 
+0

我只是簡單地添加數據類型JSON,現在我得到一個錯誤。我控制檯記錄狀態,錯誤和xhr,它沒有任何迴應。對象的xhr響應及其狀態爲200,響應文本** <?PHPhall $ data ='hello'haheader('Content-Type:application/json');↵echojson_encode($ data);↵ ?>。**狀態是**語法錯誤意外tocken <在JSON **中,錯誤消息是** parseerror ** –

+0

@BrianBier:爲什麼你使用'header('Content-Type:application/json')? ;'? – devpro

+0

我只是測試,看看是否是這個問題。但不是。 –

0

首先'hello'不是json可編碼的,你需要使用數組('result'=>'hello')。

如果您獲取php文件的內容,似乎您不使用工作的本地服務器。

0

你需要設置headerPHP發送JSON結果

試試這個

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