JSON autosave with Link

Hy!

I want to do autosuggest from my php file, which returns a Json Object. I parse it in js to get the link with the correct id (look at json)

JSON from search_new.php:

{"Data":{"Recipes":{"Recipe_5":{"ID":"5","TITLE":"Spaghetti Bolognese"},"Recipe_7":{"ID":"7","TITLE":"Wurstel"},"Recipe_9":{"ID":"9","TITLE":"Schnitzel"},"Recipe_10":{"ID":"10","TITLE":null},"Recipe_19":{"ID":"19","TITLE":null},"Recipe_20":{"ID":"20","TITLE":"Hundefutter"},"Recipe_26":{"ID":"26","TITLE":"Apfelstrudel"},"Recipe_37":{"ID":"37","TITLE":null},"Recipe_38":{"ID":"38","TITLE":"AENDERUNG"},"Recipe_39":{"ID":"39","TITLE":null},"Recipe_40":{"ID":"40","TITLE":"Schnitzel"},"Recipe_42":{"ID":"42","TITLE":"Release-Test"},"Recipe_43":{"ID":"43","TITLE":"Wurstel2"}}},"Message":null,"Code":200} 

Call in JS:

  <script type="text/javascript"> $(function() { var allRecipes = (<?php include("php/search_new.php"); ?>).Data.Recipes; var recipeNames = []; for(var i in allRecipes) { recipeNames.push("<a href=\"/php/get_recipe_byID.php?id="+ allRecipes[i].ID + "\">" + allRecipes[i].TITLE) + "</a>"); } var arr = new Array(); for(var k in recipeNames){ arr.push(" " + recipeNames[k]); } $("#searchrecipes").autocomplete({ minLength: 3, source: arr }); }); </script> 

Firebug Error:

is absent; before the expression recipeNames.push ("+ allRecipes [i] .TITLE) +" ");

Before I had recipeNames.push("allRecipes[i].TITLE)"); everything worked well

Please, help.

+4
source share
2 answers

Yes, I see your problem. Here is the code you need:

 $(function() { var data = (<?php echo file_get_contents("php/search_new.php"); ?>).Data.Recipes; var source = []; for (var i in data) { source.push({"href": "/php/get_recipe_byID.php?id=" + data[i].ID, "label": data[i].TITLE}); } $("#searchrecipes").autocomplete({ minLength: 3, source: source, select: function(event, ui) { window.location.href = ui.item.href; } }); }); 

Here you can find an example: http://jsfiddle.net/dFApV/

0
source

surely an extra bracket has been added for all the Recipes [i] .TITLE that need to be deleted !: D

I would say you can achieve the same result, but with a much more pleasant solution using the .result method. Tell me what you think about it!

JQuery API Autocomplete Result

0
source

Source: https://habr.com/ru/post/1380743/


All Articles