用jquery json从php获取变量

时间:2014-05-22 17:28:52

标签: javascript php jquery ajax json

我试图从jquery json获取php的几个变量结果。问题是我在控制台中获取空值(例如标题上)并且脚本失败。使用此脚本,我尝试使用从php发送的数据填充一些输入字段。我是ajax json的菜鸟。请帮帮我。

HTML

<input id="titledata" type="text" name="siteTitle" value="" />
<textarea id="itemDescription" name="description"></textarea>
<input id="suggestkeyworddata" type="text" name="proposalForKeywords" value="" />

JQUERY - 这里我试图获取变量并将它们存储到jquery变量中: var title = data.titledata;....

<script type="text/javascript">
$(function checkdomain() {
    jq2('#metaTagButtonz').on('click', function (e) {
        $.ajax({
            type: 'post',
            url: 'getallinfos.php',
            data: $('#urlpr').serialize(), // sending data to php from this field
            dataType: 'json',
            success: function (data) {
                $("#domain-hits").html(data);
                         // here i am trying to get data from php
                var title = data.titledata; 
                var description = data.descriptiondata;
                var keywords = data.keywordsdata;
                         // here I am trying to populate the data into the 
                         // input fields
                $('#titledata').val(title); 
                $('#itemDescription').val(description);
                $('#keywordswebsite').val(keywords);
            }
        });
        e.preventDefault();
    });
});
</script>

PHP

    //$title, $descr, and $keywords are strings 
    (sometimes empty sometime have values depending on the website)
$data = array(
    'titledata' => $title,
    'descriptiondata' => $descr,
    'keywordsdata' => $keywords,
);
$data = json_encode($data);

1 个答案:

答案 0 :(得分:2)

您只需要从php脚本中打印实际内容:

header('Content-Type: application/json');
echo json_encode($data);