如何使用javascript forloop删除json中的最后一个逗号

时间:2016-05-10 06:23:54

标签: javascript php json

    $('#save').click(function() {
    var loopvalue = "<?php echo $count; ?>"
    var datajson = '[';
    //alert(loopvalue + "length of array")
    for (i = 1; i < loopvalue; i++) {
        var fetchid = '.A' + i;
        var fetchid_code = '.C' + i;
        datajson = datajson + "{" + "maincode :" + $('#company').val() + ",acode : " + $(fetchid_code).text() +
            " , Amount :" + $(fetchid).val() + ", periodfrom :" + $('#dFrom').val() +
            ", periodto : " + $('#dTo').val() + ", danounc : " + $('#dano').val() +
            ", period : " + $('#period').val() + ", fyear : " + $('#fyear').val() +
            ", frequency : " + $('#freq').val() + ", stype : " + $('#stype').val() +
            ", sseq : " + $('#sseq').val() + " }, "

    }
    datajson = datajson + ']'
        //console.log(datajson);

    $.ajax({
        type: 'POST',
        url: 'jsondecode.php',
        data: {
            datajson: JSON.stringify(datajson)
        },
        //data:postArray,
        dataType: "json",
        success: function(data) {
            console.log("success:", data);
        },
        failure: function(errMsg) {
            console.error("error:", errMsg);
        }
    });
});

首先删除json对象中的最后一个逗号,然后在我调用ajax页面时显示第二个逗号,但它在jsonencode.php页面中显示NULL值如何才能解决此问题任何建议我这是我的服务器站点脚本

 <?php
     header('Content-Type: application/json');    
    $data = json_decode($_POST["datajson"]);
// will echo the JSON.stringified - string:
echo $_POST["datajson"];
// will echo the json_decode'd object
var_dump($data);
//traversing the whole object and accessing properties:
foreach ($data as $Object) {
    echo "maincode: " . $Object->maincode . ", Acode: " . $Object->acode . "<br/>";
}
?>

3 个答案:

答案 0 :(得分:3)

或许您应该使用实际对象而不是字符串连接

试试这个

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/myCoordinator"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    app:contentScrim="?attr/colorPrimary"
    app:expandedTitleMarginEnd="64dp"
    app:expandedTitleMarginStart="48dp"
    app:layout_scrollFlags="scroll|exitUntilCollapsed">
    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <include
            layout="@layout/toolbar"/>

    </android.support.design.widget.AppBarLayout>
    <android.support.v4.widget.NestedScrollView
        android:id="@+id/myScrollingContent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <android.support.design.widget.CoordinatorLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">
                <FrameLayout
                    android:layout_weight="1"
                    android:layout_width="match_parent"
                    android:layout_height="200dp">
                    <android.support.v4.view.ViewPager
                        android:id="@+id/pagerDemo"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:background="#2c3e50"
                      />
                    </FrameLayout>

                <android.support.design.widget.TabLayout
                    android:id="@+id/tabs"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    app:tabMode="scrollable"/>



                      <android.support.v4.view.ViewPager
                          android:layout_margin="10dp"
                        xmlns:android="http://schemas.android.com/apk/res/android"
                        android:id="@+id/pager"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"/>
                    <android.support.v7.widget.AppCompatImageView
                        android:layout_width="match_parent"
                        android:layout_height="250dp"
                        android:background="#251233"/>
                <android.support.v7.widget.AppCompatImageView
                    android:layout_width="match_parent"
                    android:layout_height="250dp"
                    android:background="#4492a7"/>
                    </LinearLayout>

  </android.support.design.widget.CoordinatorLayout>
    </android.support.v4.widget.NestedScrollView>
 </android.support.design.widget.CoordinatorLayout>

main.class

public class MainActivity extends AppCompatActivity {
    ViewPager viewPager;
    ViewPager mviewPager;
    ViewFlipper viewFlipper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
//
//      toolbar1 = (Toolbar) findViewById(R.id.toolbar);
//        setSupportActionBar(toolbar1);
        viewPager = (ViewPager) findViewById(R.id.pager);
        setupViewPager(viewPager);
        mviewPager = (ViewPager) findViewById(R.id.pagerDemo);
        PagerAdapter adapter = new pageradapter(this);
        mviewPager.setAdapter(adapter);
        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);
    }

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFrag(new OneFragment(), "Top Tracks");
        adapter.addFrag(new TwoFragment(), "Fasion");
        adapter.addFrag(new ThreeFragment(), "Wheels");
        adapter.addFrag(new FourFragment(), "Clurnery");
        adapter.addFrag(new FiveFragment(), "Education");
        adapter.addFrag(new SixFragment(), "Technology");
        adapter.addFrag(new SevenFragment(), "REGGAE");
        adapter.addFrag(new EightFragment(), "PROCRESSIVE");
        viewPager.setAdapter(adapter);
    }


    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(android.support.v4.app.FragmentManager fragmentManager) {
            super(fragmentManager);
        }


        @Override
        public android.support.v4.app.Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        public void addFrag(android.support.v4.app.Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }

adapter.class

public class pageradapter extends PagerAdapter

    {
        private int[] image_resouce = {R.drawable.thired, R.drawable.apple, R.drawable.phone};
        Context context;
        public pageradapter(Context context) {
        this.context = context;

    }


        @Override
        public int getCount () {
        return image_resouce.length;
    }

        @Override
        public boolean isViewFromObject (View view, Object object){
        return (view == (LinearLayout) object);
    }

        @Override
        public Object instantiateItem (ViewGroup container,int position){
        LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View itemView = layoutInflater.inflate(R.layout.pageview, container, false);

        ImageView im = (ImageView) itemView.findViewById(R.id.imPager);

        im.setImageResource(image_resouce[position]);

        container.addView(itemView);
        return itemView;
    }

        @Override
        public void destroyItem (ViewGroup container,int position, Object object){
        container.removeView((LinearLayout) object);
    }
    }

答案 1 :(得分:0)

将外观的单个元素写入数组,然后加入元素。

见这里:javascript join

但是当然自己构建JSON是没有必要的。请使用JSON.stringify

答案 2 :(得分:0)

在您将]追加到datajson之前,substring该值将删除上一个,。就是这样。

datajson = datajson.toString().subString(0, datajson.toString().length - 1);

然后附加]

由于您要发送json字符串,因此不需要在JSON.stringify(datajson)的{​​{1}}属性中使用data。不是json对象。

希望这有帮助