繁体   English   中英

如何获取PHP JSON编码的对象作为Javascript / JQuery上的变量?

[英]How can I get a PHP JSON-encoded object as a variable on Javascript/JQuery?

因此,我使用PHP进行服务器端脚本编写,php接收一个字符串作为HTTP GET请求,最后,它回显JSON对象。

如何在JavaScript上使用Javascript / JQuery将此JSON回显作为'var'? 我想将此JSON对象用于客户端脚本。

$query = trim(strtolower($_GET["query"]), "?");
$stopList = array("much", "many", "the", "who", "what", "where", "when", "why", "how", "a", "is", "which", "so", "were", "there", "this", "did", "was", "will", "are", "you", "do", "I", "it", "are", "can", "i", "he", "she", "you", "did");
$templateFile = fopen("templates.txt", "r");
$templateList = array();
while(!feof($templateFile)) {
    array_push($templateList, fgets($templateFile));
}
fclose($templateFile);
$index = rand(0, count($templateList) - 1);
$template = $templateList[$index];
function makeTemplate($template, $subject, $stopList) {
    $listWords = explode(" ", $subject);
    $goodList = array_diff($listWords, $stopList);
    $answer = implode(" ", $goodList);
    $response = str_replace('#word', $answer, $template);
    return $response;

}
function containsUnwantedSymbol($haystack) {
    return substr($haystack, 0 , 1) === "#" || substr($haystack, 0, 1) === "@" || substr($haystack, 0, 4) === "http" || substr($haystack, 0, 5) === "https";;
}
require_once("TwitterAPIExchange.php");
$settings = array(
    "oauth_access_token" => "OAUTH_ACCESS_TOKEN_HERE",
    "oauth_access_token_secret" => "OAUTH_ACCESS_TOKEN_SECRET_HERE",
    "consumer_key" => "CONSUMER_KEY_HERE",
    "consumer_secret" => "CONSUMER_SECRET_HERE"
);
$url = "https://api.twitter.com/1.1/search/tweets.json";
$requestMethod = "GET";
$getField = "?q=".$query;
$twitter = new TwitterAPIExchange($settings);
$response = $twitter->setGetfield($getField)
                        ->buildOauth($url, $requestMethod)
            ->performRequest();
$details = json_decode($response, true);
$tweet = $details['statuses'][0]['text'];
$list = explode(" ", $tweet);
$against = array();
for($item = 0; $item < count($list); $item++) {
    if($list[$item] == "RT") {
        unset($list[$item]);
    }
}
for($item = 0; $item < count($list); $item++) {
    if(containsUnwantedSymbol($list[item]) || containsUnwantedSymbol($list[$item]) || containsUnwantedSymbol($list[$item])) {
        unset($list[$item]);
    }
}
$tweet = implode(" ", $list);
$dreet = makeTemplate($template, $query, $stopList);
$clauses = array("durhamResponse" => $dreet, "twitterResponse" => $tweet);
shuffle($clauses);
$json_clauses = json_encode($clauses);

echo $json_clauses;

请注意,在底部,我已经回显了我想在Javascript中使用的JSON对象。 如何从php中获取此对象作为var以在Javascript中使用?

$(document).ready(function() {
    $('#question').on('submit', function() {
        event.preventDefault();
        $.get("durhamServer.php", function() {
            $('#response1').load("durhamServer.php", $('#request').serialize());
        });
    });
});

此Javascript代码将php echo的值显示到HTML页面。 我要如何直接在客户端上获取此值作为javascript上的var值

像这样:

$.ajax({
    type: "GET", 
    url: url,
    success: function(response) {
        var variables = response;
    }
});

首先,您将使用JQuery的Ajax获取您的PHP URL

http://api.jquery.com/jquery.ajax/

$.ajax({
  method: "GET",
  url: <your php url>,
  success : <a function to handle the success>,
  error : <a function to handle any errors>
})

您的“呼应” PHP内容将被处理success函数(或error ,如果有任何错误,如404500等)

因此,您的success功能是应该对来自服务器的数据进行处理的功能。 在JQuery文档中,这是JQ安排来自服务器的数据的方式:

Function( Anything data, String textStatus, jqXHR jqXHR )

因此,您回显的php数据包含在第一个参数中,即data

success : function(myPhpData, textStatus, jqXHR){
    // your echoed php data is now on myPhpData and you can do whatever you want with it
}

请记住,Ajax调用是异步的:仅在服务器响应后, success函数才会执行。 如果在ajax调用之后编写任何内容,则可能会出现竞争状况的风险-因此,请学习如何控制JavaScript代码流。

暂无
暂无

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

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