开发者

How to make string as an Array Object in JQuery

I have got below string values in a variable.

var mystring = '{"img_src":"/english/images/spa.jpg",
    "img_title":"Enjoy a refreshing shower at 43,000 feet",
    "img_alt":"Enjoy a refreshing shower at 43,000 feet",
    "img_height":"326",
    "img_width":"980",
    "header":"Enjoy a refreshing shower at 43,000 feet",
    "subheader":"One of many groundbreaking amenities",
    "bg_color":"",
    "url_href":"1"}, 
     {"img_src":"/english/images/spa1.jpg",
    "img_title":"Enjoy a refreshing shower at 43,000 feet",
    "img_alt":"Enjoy a refreshing shower at 43,000 feet",
    "img_height":"326",
    "img_width":"980",
    "header":"Enjoy a refreshing shower at 43,000 feet",
    "subheader":"One of many groundbreaking amenities",
    "bg_color":"",
    "url_href":"1"}'

Now I want to convert this string variable into Array object. So that If I try to access it my function it should behave like an array object. For example.

some code to Convert(mystring) to开发者_高级运维 an Array Object(myArryObject), then I want to pass it to my function like below

$.fn.liveBanner = function(myArryObject,optional_options) 
    { 
      //here I want to access my myArryObject as below
      alert(myArryObject[0].img_src) //then it should give "/english/images/spa.jpg"
});

Please suggest using JQuery.

EDIT:

I did the changes as suggested by @Deceze, please see below:

             var myString = "'"+ $("#RotationImages #mainHidden").attr("value")+"'";     

    var myArrayobj = jQuery.parseJSON('[' + myString + ']');
    alert(myArrayobj.img_src);

the above code is giving below error

Error: uncaught exception: Invalid JSON:'{"img_src":"/english/images/spa.jpg", "img_title":"Enjoy a refreshing shower at 43,000 feet","img_alt":"Enjoy a refreshing shower at 43,000 feet", "img_height":"326","img_width":"980","header":"Enjoy a refreshing shower at 43,000 feet","subheader":"One of many groundbreaking amenities on the Flight","bg_color":"","url_href":"1"}'


As your string only contains the objects inside the array, you have to add the array declaration before you parse it:

var myArrayobj = jQuery.parseJSON('[' + myString + ']');


Given your mystring as defined, executing var myArray = jQuery.parseJSON('[' + mystring } ']'); will result in an array of objects. See this jsfiddle for a live example.

The reason you are getting the invalid JSON error is because you wrap your valid JSON in single quotes, thereby making it invalid. That is, the first line in:

var myString = "'"+ $("#RotationImages #mainHidden").attr("value")+"'";     

var myArrayobj = jQuery.parseJSON('[' + myString + ']');
alert(myArrayobj.img_src);

is invalidating your JSON. The first line should be (provided the value is correct):

var myString = $("#RotationImages #mainHidden").attr("value");

For more information on JSON see json.org and RFC 4627.


Well, for a start, your inputs have the type="hidden" which means that no matter what jQuery you run on the surrounding div, these elements are never going to appear. If your bounding div has "display:none" then there's no reason to have the input type set to hidden.

You really need to revise the way you've written this code. You should have a stylesheet to hide the images (which you should place in the code as images) and then you can use the javascript to show them. You could use the jQuery UI Tabs demo as a guide how to properly structure the markup and then go from there.

Is there a specific reason you used inputs for the images?


Ok, your still not going in the right direction here.

Your jQuery has the following:

.attr('type','hidden').

This segment is setting the type to hidden. You're then writing the output to the screen.

Change this to:

.attr('type','image').

And see if that makes a difference (you will have to create an unset function where you change it back to "hidden" when you are done).

Like I say, this is really not the cleanest way to do what you are trying to do, but I can't point you any other way than to suggest you try again using a different method.


Finally I was able to write some JQuery which help me to resolve my problem, now I am able to get my desired HTML. Below is the JQuery code, please have a look and let me know for any improvement.

$(document).ready(function()
{
        var rotationImagelength = $('#RotationImages input[type=hidden]').length; //Getting the length of the Rotation Image Input type hidder
        var ImageDetail; 
        var $addDetails="";
        var fromPageInput = $("<input>").attr("id", "mainHidden").attr("type", "hidden").attr("name", "fromPage").val(ImageDetail); //Generating the dynamic input type hidden  

        $('#RotationImages input[type=hidden]').each(function(index,element) //Loop for all the input type hidden in RotationImage DIV
        {   

            if(index != rotationImagelength - 1) //Loop for checking not the last input hidden, we are adding extra Comma(,)
            {                    
                ImageDetail = '{"img_src":"'+ $(element).attr("src")+'", "img_title":"'+ $(element).attr("title")+'","img_alt":"'+ $(element).attr("alt")+'", "img_height":"'+ $(element).attr("height")+'","img_width":"'+ $(element).attr("width")+'","header":"'+ $(element).attr("header")+'","subheader":"'+ $(element).attr("subheader")+'","bg_color":"'+ $(element).attr("color")+'","url_href":"'+ $(element).attr("href")+'"},';                                                  
                $addDetails += ImageDetail;
            }    
            else //Generating HTML for the last input hidden
            {
                ImageDetail = '{"img_src":"'+ $(element).attr("src")+'", "img_title":"'+ $(element).attr("title")+'","img_alt":"'+ $(element).attr("alt")+'", "img_height":"'+ $(element).attr("height")+'","img_width":"'+ $(element).attr("width")+'","header":"'+ $(element).attr("header")+'","subheader":"'+ $(element).attr("subheader")+'","bg_color":"'+ $(element).attr("color")+'","url_href":"'+ $(element).attr("href")+'"}';                                                            
                $addDetails += ImageDetail;
            }                

            $(fromPageInput).val($addDetails); //Adding full values in the dynamic input hidden created above    


        });
         $("#RotationImages").append($(fromPageInput)); //Appending to the RotationImage DIV so that we can easily use in JQuery.
         var test = ($("#RotationImages #mainHidden").attr("value"));
         alert(test);
});

Thanks for your help, your suggestion is always welcome


You need to use a javascript var (I think):

gImgs = [
    {"img_src":"/english/images/spa.jpg",
    "img_title":"Enjoy a refreshing shower at 43,000 feet",
    "img_alt":"Enjoy a refreshing shower at 43,000 feet",
    "img_height":"326",
    "img_width":"980",
    "header":"Enjoy a refreshing shower at 43,000 feet",
    "subheader":"One of many groundbreaking amenities",
    "bg_color":"",
    "url_href":"1"}
];

then

$('.slideshow').liveBanner(gImgs, {"autostart":false, 
  "pause_time":5500, "random":false});

So on each page you will have a different gImgs. Note that if you include a script for the liveBanner creation, you will have to define gImgs before the <script src="..."></script>, like:

<html>
    <head>
        <!-- ... -->
        <script type="application/x-javascript">
        <!--
            var gImgs = [ /* ... */ ];
        -->
        </script>
        <script type="application/x-javascript" src="yourscript.js"></script>
    </head>
    <body>
    <!-- ... -->
    </body>
</html>


Try jQuery.parseJSON.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜