如何从jQuery $ .get评估数据返回布尔值

时间:2011-07-02 03:26:53

标签: php jquery

$('#my_theme').click
(
    function() 
    {
    $('#my_theme option').each(function(){
    //how do I test for this $.get to return true?
        if ($.get('<?php echo get_bloginfo('template_directory') ?>/getStyle.php', {template: $(this).val()})==true)
            {
                $(this).attr("disabled","disabled");
            }
    });

    }
);


<?php
//getStyle.php

$myTemplate = $_REQUEST['template'];

$file = "styles/".$myTemplate."/style.css";
    if (file_exists($file))
    {
    return true;
    }
    else
    {
    return false;
    }
?>

3 个答案:

答案 0 :(得分:2)

Javascript和服务器端语言只能使用 text 进行通信。无法发送简单的布尔truefalse,您只能将其作为'0''1'或其他任何值发送。此外,return不会输出任何内容,因此您的Javascript只会返回一个空字符串,其结果为false。您需要发送一些特定的字符串,或者更好的是JSON:

// PHP
echo json_encode(file_exists($file));

// Javascript
$.getJSON(…)

http://api.jquery.com/jQuery.getJSON/

答案 1 :(得分:0)

如果您的代码返回的回复如下:

// more code here
$Response = array('Success' => true);
echo json_encode($Response);

然后在你的JS中你可以这样做:

$.get('<?php echo get_bloginfo('template_directory') ?>/getStyle.php', 
        {template: $(this).val()}, function(response) 
{
   if (response.Success)
      $(this).attr("disabled","disabled");

}, "json");

答案 2 :(得分:0)

 //php
 $res = new StdClass();
 $res->Success = (file_exists($file));
 json_encode($res);

 // jquery
 var obj = jQuery.parseJSON('{"Success": true}');
 alert( obj.Success === true );