[英]Javascript Data Format, Is This JSON?
我使用的一些 jquery 插件需要這種格式的數據作為其輸入類型
[
{image : '1.jpg', title : 'Title', url : '', age : 24, location : 'US', name : 'John', description : 'Long Text'},
{image : '1.jpg', title : 'Title', url : '', age : 24, location : 'US', name : 'John', description : 'Long Text'},
{image : '1.jpg', title : 'Title', url : '', age : 24, location : 'US', name : 'John', description : 'Long Text'}
]
我的問題是,這種數據是什么以及如何創建它? 這還是 JSON 嗎? 因為當我嘗試使用 PHP 傳遞 json_encoded 數組並使用 jquery 獲取它時,我得到了這種格式:
[
{'image' : '1.jpg', 'title' : 'Title', 'url' : '', 'age' : 24, 'location' : 'US', 'name' : 'John', 'description' : 'Long Text'},
{'image' : '1.jpg', 'title' : 'Title', 'url' : '', 'age' : 24, 'location' : 'US', 'name' : 'John', 'description' : 'Long Text'},
{'image' : '1.jpg', 'title' : 'Title', 'url' : '', 'age' : 24, 'location' : 'US', 'name' : 'John', 'description' : 'Long Text'}
]
注意包裹變量名的引號。 這使代碼無法正常工作。
插件似乎不需要 JSON - 看起來更像某種字典。
有效的 JSON 看起來類似於: {"name":"John", "age":50}
您可能需要構建一個自定義幫助方法來為您的插件正確格式化數據,如果您提供更多源代碼可以幫助您:)
我將把這是另一個答案,這樣更容易閱讀......
在這種情況下,您不想生成 JSON,插件需要一個文字數組,正如 Matt Ball 所說。
基本代碼格式將與此類似(將是半 .NET 抱歉......):
public Array GenerateData()
{
// Generate dynamic data here and return as a list / array
}
// Get the data
Array dynamicData = GenerateData();
// Create the template
string template = "[";
// For each item in list, add to the template
foreach (item in dynamicData)
{
template += "{ image : '" + item[0] + "', title : '" + item[1] + "', url : '" + item[2] + "', age : " + item[3] + ", location : '" + item[4] + "', name : '" + item[5] + "', description : '" + item[6] + "' },"
}
// Add closing brack - may need to trim off last comma also?
string template = "]";
然后將模板字符串嵌入到您的插件初始化中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.