在这种情况下你有把ajax值放到php字符串中的方法吗?

时间:2015-02-26 18:54:56

标签: php jquery ajax

我想知道你是否有办法将ajax结果放入php字符串中。在ajax成功中:你有其他方法来返回除.html().text().val()以外的结果,所以我可以直接将结果放入php字符串而不是html。< / p>

jQuery.ajax({
    url:'member_search.php',
  	type:'POST',
  	data:{ 		
  	    search_text: $(".result_tag").text()  			
    },
  	error: function(){
  	    $('#find_members').html('<p>An error has occurred</p>');
  	},
  	success: function(data){
	    $("#get_user").text(data);
    }
});
<?php
$user=//the result of ajax return.

?>

3 个答案:

答案 0 :(得分:0)

你的ajax请求是客户端的,你的PHP是服务器端的,所以这是不可能的。

member_search.php收到ajax请求时,应该完成所有工作。通过再次将结果发送给PHP,你无法做到。

答案 1 :(得分:0)

您面临的问题是因为您从AJAX发送数据并从服务器接收数据时感到困惑。请参阅以下示例并根据您的需要进行更改。

<form class="search" action='results.php'>
<input type='text' name='keyword' >
</form>

你的AJAX请求看起来像。

$(".search").submit(function (event) {
            event.preventDefault();

            $.ajax({
                url: $(this).attr('href'),
                data: $(".search").serialize(),
                type: "POST",
                dataType: 'json',
                success: function (res) {
                    if (res.status) {
                        //Your success results or keywords
                       $("#get_user").text(res.output);
                    }
                }
            });
            return false;
        })

在你的result.php文件中你应该根据用户输入的关键字使用select查询,或者我可以说在这里输入逻辑代码

    <?php if($_POST){
    //You will receive form post data and put your conditional logics

    //at last please make sure to encode your data first to transfer to AJAX. Like
    $res = array();
    $res['status'] = true;
    $res['output'] = YOUR DESIRED OUTPUT;
    echo json_encode($res); exit; 
    }
?>

答案 2 :(得分:0)

PHP是一种服务器端语言。这意味着它在呈现html之前在服务器上执行。 php中的所有变量都是赋值,并在服务器端本身消耗。现在,只要将任何内容发送到本地计算机,就会发生这种情况。当你看到DOM时,所有的变量都完成了它们的工作,而DOM只不过是生成的渲染。

AJAX请求从本地计算机(客户端)发送到服务器,它们从服务器请求数据或在服务器上放入一些数据。现在,如果您在帖子中有代码,它将在服务器端工作。这就是你消费整个事情的方式:

客户端代码:

    $.ajax({
        url: '/path/to/php/file/or/function',
        type: 'default GET (Other values: POST)',
        dataType: 'default: Intelligent Guess (Other values: xml, json, script, or html)',
        data: {param: 'value'}, //these are the values you send
    })
    .done(function(receivedData) {
        alert(receivedData);
        console.log("success");
    })
    .fail(function() {
        console.log("error");
    })
    .always(function() {
        console.log("complete");
    });

这是您的服务器端代码:

<?
  function iReceivedTheData(){
    if($_POST){
        $serverSideVar = param; //this is the item you sent from the ajax request
        $response = someThingElse($serverSideVar); //this is where you do what you need to with the data you received and log that into a variable called response

        echo $response; //this is where you give the response back to the client side. this response will be the 'data' that you receive on success of the ajax request, i have alerted the same above.
    }
  }
 ?>

这就是你如何在服务器端使用客户端值