2017-08-01 60 views
-1

我试图找出如何使用AJAX例如只是显示从PHP特定的响应只显示来自服务器的特定回波响应。我有一个PHP这给下面的响应 -是有可能用ajax

echo 'Success'; //Display only this 

//Some other process 

echo 'Something else for other process'; 

JS

$.ajax({ 
    type: "POST", 
    url: "some.php", 
    data: {action: 'test'}, 
    dataType:'JSON', 
    success: function(response){ 
     $('#name_status').html(response); 
    } 
}); 
+1

只是改变'数据类型: 'JSON''为'数据类型:' HTML'' –

回答

0

使用if else

而且在发送Ajax请求,发送条件参数。例如,flag:将其设置为yesno

获取这些参数在PHP后端$_POST版。

取决于AJAX的值发送参数,打印响应。

JS:

$.ajax({ 
type: "POST", 
url: "some.php", 
data: {action: 'test', 'flag' : 'yes'}, 
dataType:'JSON', 
success: function(response){ 
    $('#name_status').html(response); 
} 
}); 

设置flagyesno //这只是样品。

在PHP中,

if (isset($_POST['flag'] && $_POST['flag'] == 'yes') { 
    echo 'Success'; //Display only this 
} 
else { 
    echo 'Something else for other process'; 
} 
0

你将不得不发送json_encode接收JSON响应,将不得不相应地改变PHP了。下面是更新后的代码,你可以尝试:

PHP:

if($_POST['action'] == 'test') { 
    $returnArray = array('message' => 'Success'); 
} else { 
    $returnArray = array('message' => 'Something else for other process'); 
} 
echo json_encode($returnArray); 

JS

$.ajax({ 
    type: "POST", 
    url: "some.php", 
    data: { 
    action: 'test' 
    }, 
    dataType: 'JSON', 
    success: function(response) { 
    var responseObj = jQuery.parseJSON(response); 
    $('#name_status').html(responseObj.message); 
    } 
}); 
+0

我无法打印$('#name_status')。html(response.message);如果我从中删除消息,我可以打印。 –

+0

你检查控制台吗?另外补充'在成功函数'的console.log(响应),并检查您在控制台正在接受什么。 –

+0

console.log(response)result - {“message”:“Success”}&console.log(response.message)result - “undefined” –

相关问题