首页 \ 问答 \ 搜索不使用jQuery调用json(Search not working using jQuery with call to json)

搜索不使用jQuery调用json(Search not working using jQuery with call to json)

我想要做的是,我有一个输入字段。 在输入字段中输入内容时,如果我发送请求到输出json的php文件,我想要的是根据搜索字段中的输入从json获取结果。

的index.html

<input type="text" id="search-json-input" />
<input type="button" id="search-json-submit" value="search" />
<br/>
<br/>
<input type="button" name="next" id="next" value="NEXT" />
<br/>
<input type="button" name="previous" id="previous" value="PREV" />
<br/>

<div id="divuseriemail"></div>
<div id="divusersex"></div>
<div id="divuserlocation"></div>
<div id="divuserimage"></div>
<div id="divuseraudio"></div>
<div id="divuservideo"></div>


<script type="text/javascript">

var users = [];
var idx = 0; 

var url = "json.php";
var search_query = jQuery('#search-json-input').val();
var search_query_regex = new RegExp(".*"+search_query+".*", "g");
$.getJSON(url, function (data) {

    users = data.members;

    renderRow(idx);
    $('#next').click(function() {
        idx++;
        renderRow(idx);
    });
    $('#previous').click(function() {
        idx--;
        renderRow(idx);
    });
});

$("#search-json-submit").click(function(){


    for(var y=0;y<users.length;y++){ 
        //console.log(users[y]);
        if((users[y].email).match(search_query_regex) ||
            (users[y].sex).match(search_query_regex) ||
            (users[y].location).match(search_query_regex)) 
        {
            //console.log(users[y].email);
            renderRow(y)
        }
     }
});

var renderRow = function (idx) {
    //alert(idx);
    if (idx < 0) idx = 0;
    if (idx > (users.length - 1)) idx = (users.length - 1);
    var user = users[idx];

    var email = user.email;
    $('#divuseremail').html(email);
    var sex = user.sex;
    $('#divusersex').html(sex);
    var location = user.location;
    $('#divuserlocation').html(location);
    var image = "<img src=" + user.image + ">";
    $('#divuserimage').html(image);
    var audio = "<audio src=" + user.video + " controls>";
    $('#divuseraudio').html(audio);
    var video = "<video src=" + user.video + " controls>";
    $('#divuservideo').html(video);
};

</script>

json输出: http//sco7.com/components/phonegap/json.php


What i am trying to do is, i have an input field. Upon entering something in the input field if am sending request to the php file which outputs json, what i want is to get the results from the json based on the input in the search field.

index.html

<input type="text" id="search-json-input" />
<input type="button" id="search-json-submit" value="search" />
<br/>
<br/>
<input type="button" name="next" id="next" value="NEXT" />
<br/>
<input type="button" name="previous" id="previous" value="PREV" />
<br/>

<div id="divuseriemail"></div>
<div id="divusersex"></div>
<div id="divuserlocation"></div>
<div id="divuserimage"></div>
<div id="divuseraudio"></div>
<div id="divuservideo"></div>


<script type="text/javascript">

var users = [];
var idx = 0; 

var url = "json.php";
var search_query = jQuery('#search-json-input').val();
var search_query_regex = new RegExp(".*"+search_query+".*", "g");
$.getJSON(url, function (data) {

    users = data.members;

    renderRow(idx);
    $('#next').click(function() {
        idx++;
        renderRow(idx);
    });
    $('#previous').click(function() {
        idx--;
        renderRow(idx);
    });
});

$("#search-json-submit").click(function(){


    for(var y=0;y<users.length;y++){ 
        //console.log(users[y]);
        if((users[y].email).match(search_query_regex) ||
            (users[y].sex).match(search_query_regex) ||
            (users[y].location).match(search_query_regex)) 
        {
            //console.log(users[y].email);
            renderRow(y)
        }
     }
});

var renderRow = function (idx) {
    //alert(idx);
    if (idx < 0) idx = 0;
    if (idx > (users.length - 1)) idx = (users.length - 1);
    var user = users[idx];

    var email = user.email;
    $('#divuseremail').html(email);
    var sex = user.sex;
    $('#divusersex').html(sex);
    var location = user.location;
    $('#divuserlocation').html(location);
    var image = "<img src=" + user.image + ">";
    $('#divuserimage').html(image);
    var audio = "<audio src=" + user.video + " controls>";
    $('#divuseraudio').html(audio);
    var video = "<video src=" + user.video + " controls>";
    $('#divuservideo').html(video);
};

</script>

json output: http://sco7.com/components/phonegap/json.php


原文:https://stackoverflow.com/questions/18055410
更新时间:2020-10-25 14:10

最满意答案

每次搜索框时,您都没有获得输入字段的.val() 。 每次执行搜索时都需要重新填充search_querysearch_query_regex ,否则您只需要使用输入字段的原始值进行搜索 - 显然,这是一个空字符串。

尝试这个:

$("#search-json-submit").click(function(){

    // re-populate variables

    search_query = jQuery('#search-json-input').val();
    search_query_regex = new RegExp(".*"+search_query+".*", "g");

    for(var y=0;y<users.length;y++){ 

        if((users[y].email).match(search_query_regex) ||
            (users[y].sex).match(search_query_regex) ||
            (users[y].location).match(search_query_regex)) 
        {
            console.log(users[y].email);
            renderRow(y)
        }
     }
});

无论有没有成功匹配,都会产生视觉反馈。 只有在搜索成功的情况下,您最好不要给成员提供反馈。 但这只是一个用户体验关注点,我相信你已经知道了。


I made some changes to my code and now everything is working.

Here is the working code:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery PHP Json Response</title>
<style type="text/css">
div
{
text-align:center;
padding:10px;
}

#msg {
width: 500px;
margin: 0px auto;
}
.members {
width: 500px ;
background-color: beige;
}
</style>
</head>
<body><input type="text" id="search-json-input" />
<input type="button" id="search-json-submit" value="search" />
<br/>
<br/>
<input type="button" name="next" id="next" value="NEXT" />
<br/>
<input type="button" name="previous" id="previous" value="PREV" />
<br/>
<div id="divuseriemail"></div>
<div id="divusersex"></div>
<div id="divuserlocation"></div>
<div id="divuserimage"></div>
<div id="divuseraudio"></div>
<div id="divuservideo"></div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<script type="text/javascript">



var users = [];
var idx = 0; 

var url = "json.php";

$.getJSON(url, function (data) {
    users = data.members;
    renderRow(idx);
    $('#next').click(function() {
        idx++;
        if (idx > (users.length - 1)) idx = (users.length - 1);
        renderRow(idx);
    });
    $('#previous').click(function() {
        idx--;
        if (idx < 0) idx = 0;
        renderRow(idx);
    });
});

$("#search-json-submit").click(function(){

        var search_query = jQuery('#search-json-input').val();
    var search_query_regex = new RegExp(".*"+search_query+".*", "g");


    for(var y=0;y<users.length;y++){ 
    if((users[y].email).match(search_query_regex) ||
           (users[y].sex).match(search_query_regex) ||
   (users[y].location).match(search_query_regex)) {

        renderRow(y)

        }
     }
});

var renderRow = function (idx) {
    //alert(idx);
   // if (idx < 0) idx = 0;
    //if (idx > (users.length - 1)) idx = (users.length - 1);
    var user = users[idx];

        console.log(user);
 var email = user.email;
   $('#divuseremail').html(email);
    var sex = user.sex;
    $('#divusersex').html(sex);
    var location = user.location;
    $('#divuserlocation').html(location);
    var image = "<img src=" + user.image + ">";
    $('#divuserimage').html(image);
    var audio = "<audio src=" + user.video + " controls>";
    $('#divuseraudio').html(audio);
    var video = "<video src=" + user.video + " controls>";
    $('#divuservideo').html(video);



};

</script>
</body>
</html>
2013-08-06

相关问答

更多

使用PHP从Vine API获取JSON并使用Jquery Ajax调用它(Get JSON from Vine API with PHP and call it with Jquery Ajax)

啊愚蠢的错误,我只需要从php中删除json_decode ,因为URL已经以正确的格式返回JSON以进行Ajax调用。 另外一个问题:这是构建此Feed的好方法吗? 有什么缺点以及可以提出什么建议来加强它(比如尽快制作或“最佳实践”选项)? Ahh stupid misstake, i just had to remove json_decode from the php because the URL already returns the JSON in the right format f ...

最好的方式是展示jQuery json调用结果的局部视图(whats the best way to show a partialview on the results of a jquery json call)

我假设你使用MVC Ajax助手来调用你的控制器来获得你的JSon结果? 另一种方法是使用JQuery调用你的JSon控制器。 因此,在链接或按钮上点击,您可以调用一些JavaScript,从隐藏的标签中找到需要传递给控制器的标识。 当您收到JSon结果时,您只需设置html标记的属性并显示/隐藏详细信息窗格。 像这样的东西: function ShowPartial() { var ID = $("#hiddenValue").attr("value"); $.getJSON("Yo ...

jquery ui autocomplete和json调用(jquery ui autocomplete and json call)

你不应该return数据,你应该将它传递给response回调。 success: function(data) { response(data); } 这几乎是一样的: success: response You're not supposed to return the data, you're supposed to pass it to the response callback. success: function(data) { response(data); } ...

jQuery Ajax调用无法在IE中运行,JSON响应无法通过(jQuery Ajax call not working in IE, JSON respond not getting through)

经过长时间的调试,我发现了这一点 data: new FormData(this), 不包括IE中的提交按钮,但在所有其他浏览器中都有。 所以要解决它,我刚刚删除: if(isset($_POST['submit_login'])) { 问题解决了:) After a long time debugging, i found out that data: new FormData(this), doesn't include the submit button in IE ...

如何使用jquery使用json响应调用ajax请求?(How to call ajax request with json response using jquery?)

您可能错过了添加type // GET或POST,哪种类型的REST OPEATION dataType被拼错了 错过了添加contentType $.ajax({ type: "POST", //rest Type dataType: 'jsonp', //mispelled url: "http://json-cricket.appspot.com/score.json", async: fals ...

PHP json_encode数据到jQuery for AJAX调用(PHP json_encode data to jQuery for AJAX call)

使用json_encode ,您不必引用结果,它已经被引用。 所以改变 sendbody = "<?php echo json_encode($test); ?>"; 至 sendbody = <?php echo json_encode($test); ?>; 否则你得到: // this cause syntax error sendbody = ""xxxxxxx""; When using json_encode, you don't have to quote the resu ...

jquery json打电话不工作(jquery json call not working)

打印,whatserver返回。 像:console.debug(data); 尝试其他json文件内容。 例如: {“one”:“奇异的感觉”,“两个”:“Beady little eyes”,“three”:“小鸟在我家门口” 祝你好运 ;-) Print, whatserver return. Something like: console.debug(data); Try other json file content. For example this: { "one": "Singul ...

使用jQuery解析和搜索JSON文件(Parse and search JSON file with jQuery)

您需要遍历sectors ,子sectors和industries阵列 var q = 'Insurance', regex = new RegExp(q, "i"); $.getJSON('models/industries.json', function (data) { $.each(data.sectors, function (i, sector) { $.each(sector.subsectors, function (i, subsector) { ...

来自Jquery的Twitter搜索无法正常工作(Twitter search from Jquery not working)

我试过你的代码,它按预期工作。 首先它提醒我一个query-string ,然后alert val 。 您可能需要注意的是什么。 确保只有一个id为提交的DOM 。 使用.on代替.click作为$ j('#submit')。on('click',function(){}); 检查jQuery是否已加载。 确保jQuery不与其他java脚本库冲突 I have tried you code and its working as expected. First its alerting me a ...

搜索不使用jQuery调用json(Search not working using jQuery with call to json)

每次搜索框时,您都没有获得输入字段的.val() 。 每次执行搜索时都需要重新填充search_query和search_query_regex ,否则您只需要使用输入字段的原始值进行搜索 - 显然,这是一个空字符串。 尝试这个: $("#search-json-submit").click(function(){ // re-populate variables search_query = jQuery('#search-json-input').val(); se ...

相关文章

更多

最新问答

更多
  • 如何保护Solr只允许SELECT请求给用户并禁止其他任何东西?(How to secure Solr to allow SELECT request to only users and disallow anything else?)
  • XPath表达式无效/错误TFHpple SWIFT 1.2(XPath Expression not working/incorrect TFHpple SWIFT 1.2)
  • css3 3D变换不能平滑地制作动画(css3 3D transform doesn't animate smoothly)
  • 运行时错误'91'和Outlook.Application = <对象变量或没有设置块变量>?(Run-time error '91' & Outlook.Application = Object variable or With block variable not set?)
  • 慢的webservice问题(Slow webservice problem)
  • textview的不正确对齐方式(Improper alignment of a textview)
  • 在第一步“Hello World”中出现Java错误(Cannot run “Hello World” program in Eclipse)
  • 为什么十六进制地址是14个字符?(why the hex address is 14 character?)
  • 如何在Python中的不同类中使用变量?(How to use variable in different classes in Python?)
  • asp:GridView HYPERLINKFIELD - datanavigateurlformatstring中的asp代码(asp:GridView HYPERLINKFIELD - asp code inside datanavigateurlformatstring)
  • 关于adaboost算法(About adaboost algorithm)
  • 在Matlab上内置图像(Built in Images on Matlab)
  • java swing:输入键事件时焦点丢失(java swing: Focus lost on enter key event)
  • C#中的通用约束,T是相同的TSomethingElse,对吧?(Generic constraints in C#, T is the same TSomethingElse, right?)
  • 从mybatis中的光标获取数据(Fetching data from cursor in mybatis)
  • 在运行时从XML构建对象的最佳方法(Best way for building objects out of XMLs at runtime)
  • 在整个窗口中拉伸sf :: Sprite(Stretch sf::Sprite across entire window)
  • Selenium Node API Web驱动程序等待超时处理程序(Selenium Node API web driver wait timeout handler)
  • 函数使用并且是map的一部分(循环依赖?)(Function uses and is part of map (circular dependency?))
  • 是否可以在C ++ 14中使用可选模板参数创建类型元组?(Is possible to make a tuple of types with optional template parameters in C++14?)
  • PHP从窗帘后面打印/ f(PHP prints /f from behind the curtains)
  • JFrame的contentPane的LayoutManager(LayoutManager of JFrame's contentPane)
  • 用于Instagram Feed的图像滚动(Image Roll Overs for Instagram Feed)
  • 如何显示拉伸字体(双倍宽度/高度)?(How to display stretched font (double width/height)?)
  • 文件操作API在fileapi.h和stdio.h中的WP8差异?(WP8 differences between file manipulation APIs in fileapi.h and stdio.h?)
  • 保存失败后Rails没有回滚事务()(Rails not rolling back transaction after failed save())
  • jqgrid中的分页问题与数组数据(Pagination problem in jqgrid with array data)
  • 重定向时,通过其他页面上的URL调用javascript函数(Call javascript function through url on otherpage while Redirecting)
  • 如何使用InvokeCommandAction调用我的方法并传入参数?(How do I go about using InvokeCommandAction to call a method of mine and pass in parameters?)
  • Jquerymobile按钮仅显示页面的第一个外观(Jquerymobile buttons are shown only first apperance of the page)